我正在尝试编写一个简单的函数来给出决选投票的结果。
我从一个包含候选名称的嵌套列表开始,我想按第一个元素对它们进行分组,并将其放入字典中(其中第一个元素是键,第一个元素是值的所有列表的嵌套列表)
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']]}
列表中的一个值(第一个)已经消失。知道为什么会这样吗?
提前谢谢你,祝你有美好的一天
我猜你想要这个
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)
groupby评论
""创建一个迭代器,从iterable Elements中返回连续的键和组,以根据键函数划分组。key用于计算每个元素的组类别的函数。如果key函数未指定或为None,则使用元素本身进行分组。"">
连续是重要的