我是一个JavaScript背景的Python新手。我正试图找到一个解决方案以下。我想动态地从列表数据构建一个字典。我只想添加计数为1的唯一列表项。之后的任何重复,我都要记录下来。因此,从包含["one", "two", "three", "one"]
的列表中,我想构建一个包含{'one': 2, 'two': 1, 'three': 1}
的字典,我的意思是使用列表条目作为键,并使用相应计数的字典值。我似乎没法让巨蟒做这件事。我的代码如下。它目前正在不可预测地增加字典的总数。我似乎只能以这种方式在列表中添加唯一的条目。算不出总数。我想问一下,我是否走错了路,或者我是否在这种方法中遗漏了什么。有人能帮帮我吗?
import copy
data = ["one", "two", "three", "one"]
new_dict = {}
# build dictionary from list data and only count (not add) any redundant entries
for x in data:
dict_copy = copy.deepcopy(new_dict) # loop through a copy (safety)
for y in dict_copy:
if x in new_dict: # check if an entry exists?
new_dict[y] += 1 # this count gives unpredictable results !!
else:
new_dict[x] = 1 # new entry
else:
new_dict[x] = 1 # first entry
print(new_dict)
使用collections.Counter
In [1]: from collections import Counter
In [2]: items = ["one", "two", "three", "one"]
In [3]: Counter(items)
Out[3]: Counter({'one': 2, 'two': 1, 'three': 1})
In [4]: dict(Counter(items))
Out[4]: {'one': 2, 'two': 1, 'three': 1}
#1这可能就是我一直在寻找的答案。
data = ["one", "two", "three", "one"]
new_dict = {}
for x in data:
if x in new_dict:
new_dict[x] = new_dict[x] + 1
else:
new_dict[x] = 1
print(new_dict)
#2使用列表推导式。
new_dict = [[x, data.count(x)] for x in set(data)]