简体   繁体   English

排列元组列表的元素

[英]Arranging elements of a list of tuples

I have a list 'l' of tuples. 我有一个元组列表“ l”。

l = [('apple',4), ('carrot',2), ('apple',1), ('carrot',7)]

I want to arrange the first elements of tuples according to the values in ascending order. 我想根据值的升序排列元组的第一个元素。

The expected result is: 预期结果是:

result = [('apple', (1,4)), ('carrot', (2,7))]

I tried as: 我尝试为:

for x in l:
  variables = list(set(x[0]))

I suppose that there is more better way of doing it. 我想有更好的方法。 Any ideas please. 有什么想法。

You could use a defaultdict to collect those values, and then get the items from the dictionary to get the desired result: 您可以使用defaultdict来收集这些值,然后从字典中获取项目以得到所需的结果:

>>> l = [('apple',4), ('carrot',2), ('apple',1), ('carrot',7)]
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, v in l:
        d[k].append(v)

>>> dict(d)
{'carrot': [2, 7], 'apple': [4, 1]}
>>> list(d.items())
[('carrot', [2, 7]), ('apple', [4, 1])]

In order to sort those sublists then, you could use a list comprehension: 为了对这些子列表进行排序,您可以使用列表理解:

>>> [(k, tuple(sorted(v))) for k, v in d.items()]
[('carrot', (2, 7)), ('apple', (1, 4))]

And if you want to sort that also by the “key”, just sort that resulting list using list.sort() . 而且,如果您还想按“键”对结果进行排序,只需使用list.sort()对结果列表进行排序。

Here's a one liner for you: 这是一个为您准备的班轮:

>>> a = [('apple',4), ('carrot',2), ('apple',1), ('carrot',7)]
>>> sorted([(n, tuple(sorted([e[1] for e in a if e[0] == n]))) for n in set(e for e,f in a)])
[('apple', (1, 4)), ('carrot', (2, 7))]

This sorts both the first element ( apple , carrot , ...), and each second element ( (1,4) (2,7) ). 这将对第一个元素( applecarrot ,...)和每个第二个元素( (1,4) (2,7) )进行排序。

Note that @poke's solution does not sort it. 请注意,@ poke的解决方案不会对其进行排序。

Here is my solution: 这是我的解决方案:

from collections import defaultdict

l = [('apple',4), ('carrot',2), ('apple',1), ('carrot',7)]

d = defaultdict(list)
for i, j in l:
    d[i].append(j)

result = sorted([tuple([x, tuple(sorted(y))]) for x, y in d.items()])

print(result)

And here is the result: 结果如下:

[('apple', (1, 4)), ('carrot', (2, 7))]

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

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