Python 排列元组列表的元素
我有一个元组列表Python 排列元组列表的元素,python,Python,我有一个元组列表 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])) 我想还有更好的办法。任何想法都可以。您可以使用收集这些值,然后从字典中获取项目以获得所需的结果: >>&g
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]))
我想还有更好的办法。任何想法都可以。您可以使用收集这些值,然后从字典中获取项目以获得所需的结果:
>>> 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()
对结果列表进行排序即可。您可以使用来收集这些值,然后从字典中获取项目以获得所需的结果:
>>> 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()
对结果列表进行排序,这里有一行代码供您使用:
>>> 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))]
这将对第一个元素(apple
,carrot
,…)和第二个元素((1,4)(2,7)
)进行排序
请注意,@poke的解决方案并没有对其进行排序。这里有一个简单的例子:
>>> 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))]
这将对第一个元素(apple
,carrot
,…)和第二个元素((1,4)(2,7)
)进行排序
请注意,@poke的解决方案不会对其进行排序。以下是我的解决方案:
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))]
以下是我的解决方案:
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))]