我试图写一个简单的函数,给出决选投票的结果。
我从一个包含候选名称的嵌套列表开始,我想按照第一个元素对它们进行分组,并将它们放入字典中(其中第一个元素是键,第一个元素的嵌套列表是值)。
def runoff_rec(xxx):
print(xxx)
sortedvotes = groupby(xxx, key=lambda x: x[0])
votesdict = {}
for key, value in sortedvotes:
votesdict[key] = list(value)
print(votesdict)
在第一次打印时,嵌套列表如下所示:
[['Johan Liebert', 'Daisuke Aramaki', 'Lex Luthor', 'Gihren Zabi'],
['Daisuke Aramaki', 'Gihren Zabi', 'Johan Liebert', 'Lex Luthor'],
['Daisuke Aramaki', 'Lex Luthor', 'Gihren Zabi', 'Johan Liebert'],
['Johan Liebert', 'Gihren Zabi', 'Lex Luthor', 'Daisuke Aramaki'],
['Lex Luthor', 'Johan Liebert', 'Daisuke Aramaki', 'Gihren Zabi'],
['Gihren Zabi', 'Daisuke Aramaki', 'Johan Liebert', 'Lex Luthor']]
但是当我印刷字典时,它看起来是这样的:
{'Johan Liebert': [['Johan Liebert', 'Gihren Zabi', 'Lex Luthor', 'Daisuke Aramaki']],
'Daisuke Aramaki': [['Daisuke Aramaki', 'Gihren Zabi', 'Johan Liebert', 'Lex Luthor'], ['Daisuke Aramaki', 'Lex Luthor', 'Gihren Zabi', 'Johan Liebert']],
'Lex Luthor': [['Lex Luthor', 'Johan Liebert', 'Daisuke Aramaki', 'Gihren Zabi']],
'Gihren Zabi': [['Gihren Zabi', 'Daisuke Aramaki', 'Johan Liebert', 'Lex Luthor']]}
列表中的一个值(第一个)消失了。知道为什么会这样吗?
提前谢谢你,祝你今天愉快
发布于 2022-07-07 03:21:08
我想你想要这个
def runoff_rec(xxx):
print(xxx)
xxx.sort(key=lambda x: x[0])
sortedvotes = groupby(xxx, key=lambda x: x[0])
votesdict = {}
for key, value in sortedvotes:
votesdict[key] = list(value)
print(votesdict)
群评
“”使迭代器从可迭代的可迭代元素中返回连续的键和组,根据键函数将其划分为组。键A用于计算每个元素的组类别。如果键函数未指定或为空,则元素本身用于分组。“
连续是重要的
https://stackoverflow.com/questions/72891769
复制相似问题