|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
请教一个问题如下
设有以下信息字符串:
myseq="""[a:1,b:2,c:3]
[a:3,b:3,c:8]
[a:7,c:2:m:7,r:4]
[a:2,c:4:m:6,r:4]
[a:3,b:2,c:7,o:5]"""
要求去除其中的重复关键字,处理结果为:
'[a:1,b:2,c:3]','[a:7,c:2:m:7,r:4]','[a:3,b:2,c:7,o:5]'
使用列表推导来处理,提取每个行中的键值,然后去除重复。
这么巧,恰好做了这道题。
- myseq = """[a:1,b:2,c:3]
- [a:3,b:3,c:8]
- [a:7,c:2,m:7,r:4]
- [a:2,c:4,m:6,r:4]
- [a:3,b:2,c:7,o:5]"""
- res_keys, res_strs = [], []
- for item in myseq.split('\n'):
- # 获取key
- item_keys = [raw_item.split(':')[0] for raw_item in item[1: len(item) - 1].split(',')]
- # 判断是否有key的列表,然后决定是否放进去。
- for key_list in res_keys: # 已存['a', 'b', 'c']
- list_r = [a for a in item_keys if a in key_list]
- long_len = len(item_keys) if len(item_keys) >= len(key_list) else len(key_list)
- if len(list_r) >= long_len:
- break
- else:
- res_keys.append(item_keys)
- res_strs.append(item)
- print(', '.join(res_strs))
复制代码
|
|