提问人:Alexander Ameye 提问时间:5/3/2017 更新时间:5/3/2017 访问量:230
使用 fromkeys 创建字典
Using fromkeys to create a dictionary
问:
我正在用 Python 写作
我有一个称为“positions”的元组列表。其中一些元组在“位置”中出现 1 次以上。我想使用代码创建一个名为 d 的字典:
d["positions"] = dict.fromkeys(positions)
这给了我一个字典,正如预期的那样,每个键的每个值都等于 None。但现在我希望这些值等于元组在“位置”中出现的次数。这是否可能而无需遍历列表“positions”或不使用类似 positions.count(x) 的东西?
亚历克斯
答:
0赞
Fuji Komalan
5/3/2017
#1
import collections
lt = [ (1,2) , (2,3) , (2,3) , (4,5) , (1,2)]
counter = collections.Counter()
counter.update(lt)
print(dict(counter))
结果
{(1, 2): 2, (2, 3): 2, (4, 5): 1}
评论
collections.Counter()