如何根据点前的字符串拆分此元素中的元素而不显式地在代码中编写它?
lst = ['ds_a.cola','ds_a.colb','ds_b.cola','ds_b.colb']
因为'ds'有两种变体。我想要两个列表
lst_dsa = ['ds_a.cola','ds_a.colb']
lst_dsb = ['ds_b.cola','ds_b.colb']
我的旧代码是:
lst_dsa = []
lst_dsb = []
for item in lst :
if "ds_a" in item:
lst_dsa.append(item)
else:
lst_dsb.append(item)
但是我不能使用这个,因为可能有超过2个,比如,ds_c,ds_d....我如何在python中实现这一点?
使用字典保存数据
from collections import defaultdict
lst = ['ds_a.cola','ds_a.colb','ds_b.cola','ds_b.colb','ds_x.cola','ds_x.colb']
data = defaultdict(list)
for entry in lst:
a,_ = entry.split('.')
data[a].append(entry)
print(data)
输出defaultdict(<class 'list'>, {'ds_a': ['ds_a.cola', 'ds_a.colb'], 'ds_b': ['ds_b.cola', 'ds_b.colb'], 'ds_x': ['ds_x.cola', 'ds_x.colb']})
尝试itertools.groupby
:
>>> from itertools import groupby
>>> [list(v) for _, v in groupby(lst, key=lambda x: x[x.find('_') + 1])]
[['ds_a.cola', 'ds_a.colb'], ['ds_b.cola', 'ds_b.colb']]
>>>
你可以映射它们:
from collections import defaultdict
lst = ['ds_a.cola','ds_a.colb','ds_b.cola','ds_b.colb']
ds_dict = defaultdict(list)
for item in lst:
key, value = item.split(".")
ds_dict[key].append(value)
print(dict(ds_dict))
输出:
{'ds_a': ['cola', 'colb'], 'ds_b': ['cola', 'colb']}
try this:
d = dict()
for item in lst:
key = item.split(".")[0]
if key not in d.keys():
d[key] = list()
d[key].append(item)
使用两个重复正则表达式:一个用于ds_a句号和一个或多个单词,一个用于ds句号和一个或多个单词。忽略空组,并使用defaultdict向集合添加值。
lst = ['ds_a.cola','ds_a.colb','ds_b.cola','ds_b.colb']
pattern=r"(?:bds_a.w+bs*)*(?:bds_b.w+bs*)*"
字符串=";, . join (lst)
groups=re.findall(pattern,string)
dict=defaultdict(set)
for group in groups:
for item in group.split():
if item !="":
print(item)
key,*value=item.split('.')
dict[key].add(value[0])
打印(dict)
输出:
defaultdict(<class 'set'>, {'ds_a': {'cola', 'colb'}, 'ds_b': {'cola', 'colb'}})