排列元组列表的元素

时间:2016-03-25 23:00:22

标签: python

我有一个列表'l'的元组。

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

我想根据值按升序排列元组的第一个元素。

预期结果是:

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

我试过:

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

我认为有更好的方法。请任何想法。

3 个答案:

答案 0 :(得分:3)

您可以使用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])]

为了对这些子列表进行排序,您可以使用列表推导:

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

如果您还想通过“密钥”对其进行排序,只需使用list.sort()对结果列表进行排序。

答案 1 :(得分:1)

这里是你的一个班轮:

>>> 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))]

这会对第一个元素(applecarrot,...)和每个第二个元素((1,4) (2,7))进行排序。

请注意,@ poke的解决方案不会对其进行排序。

答案 2 :(得分:1)

这是我的解决方案:

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)

结果如下:

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