简体   繁体   English

Python:使用 groupby 并转换为字典时,值从列表中消失

[英]Python: Value disappears from the list when using groupby and converting to a dictionary

I am trying to write a simple function that gives the result of a runoff vote.我正在尝试编写一个简单的函数来给出决选投票的结果。

I start with a nested list with names of candidates, and I would like to group them by the first element and put that into a dictionary (where the first element is the key and a nested list of all the lists with this first element is the value)我从一个包含候选人名称的嵌套列表开始,我想按第一个元素对它们进行分组并将其放入字典中(其中第一个元素是键,所有具有第一个元素的列表的嵌套列表是价值)

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)

at the first print, the nested list looks like this:在第一次打印时,嵌套列表如下所示:

[['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']]

but when I print the dictionary it looks like this:但是当我打印字典时,它看起来像这样:

{'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']]}

One of the values from the list (the first one) has disappeared.列表中的一个值(第一个)消失了。 Any idea why that might happen?知道为什么会发生这种情况吗?

Thank you in advance, have a beautiful day提前谢谢你,祝你有美好的一天

i guess u want this我想你想要这个

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 comment分组评论

""" make an iterator that returns consecutive keys and groups from the iterable iterable Elements to divide into groups according to the key function. key A function for computing the group category for each element. If the key function is not specified or is None, the element itself is used for grouping. """ """ 做一个迭代器,从可迭代的可迭代元素中返回连续的键和组,根据键函数进行分组。 key 用于计算每个元素的组类别的函数。如果键函数未指定或为None,元素本身用于分组。"""

consecutive is importan连续很重要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM