这是在Python中完成的
我有这个清单。
['arst', 'abt', 'arst', 'art', 'abrt', 'aprty', 'abt', 'arst']
我想把它放在字典中,以便所有匹配的字符串都在1键以下(与上面列表中出现的次数相同),例如:
dict = { 'arst': ['arst', 'arst', 'arst'], 'abt' : ['abt', 'abt] and so on ...
如何动态地向一个键添加多个字符串?
让:
l = ['arst', 'abt', 'arst', 'art', 'abrt', 'aprty', 'abt', 'arst']
现在,我们将遍历列表,删除重复句并创建字典:
result = {i:[i]*(l.count(i)) for i in set(l)}
给予:
{'abt': ['abt', 'abt'], 'abrt': ['abrt'], 'aprty': ['aprty'], 'art': ['art'], 'arst': ['arst', 'arst', 'arst']}
或使用Counter
模块:
from collections import Counter
result = {k:[k]*v for k,v in Counter(l).items()}
您可以使用collections.Counter
:
from collections import Counter
lst = ['arst', 'abt', 'arst', 'art', 'abrt', 'aprty', 'abt', 'arst']
dct = {k: [k] * v for k, v in Counter(lst).items()}
# {'arst': ['arst', 'arst', 'arst'],
# 'abt': ['abt', 'abt'],
# 'art': ['art'],
# 'abrt': ['abrt'],
# 'aprty': ['aprty']}
您可以简单地使用循环来获得所需的结果,使用:
d = {}
for item in lst: # lst = ['arst', 'abt', 'arst', 'art', 'abrt', 'aprty', 'abt', 'arst']
if item in d:
d[item].append(item)
else:
d[item] = [item]
print(d)
此结果字典d
为:
{'arst': ['arst', 'arst', 'arst'], 'abt': ['abt', 'abt'], 'art': ['art'], 'abrt': ['abrt'], 'aprty': ['aprty']}