简体   繁体   English

如何根据条件对压缩列表进行排序?

[英]How can i sort a zipped list based on conditions?

I'am trying to sort a zipped list based on the value. 我正在尝试根据值对压缩列表进行排序。 So the list is something like this 所以列表是这样的

[('Job 1', '3', '1'), ('Job 2', '1', '3'), ('Job 3', '2', '3'),('Job 4', '4', '3')]

What I want to do is to sort the list based on the value of the index [1] and [2] . 我要做的是根据索引[1][2]的值对列表进行排序。 For example: 例如:

Job 1         3         1
Job 2         1         3
Job 3         2         3
Job 4         4         3

If the value in column 2 is smaller than column 3, the table would become: 如果第2列中的值小于第3列,则该表将变为:

Job 2         1         3
Job 3         2         3
Job 1         3         1
Job 4         4         3

I have been searching for the method but it seems like a dead end. 我一直在寻找方法,但似乎死路一条。 So far what I found is just sort() the whole list based on the index. 到目前为止,我发现的只是基于索引对整个列表进行sort()

You could just sort it by using the keyfunc that returns index 1 and index 2 item converted to int , 您可以通过使用返回转换为int index 1index 2项的keyfunc对其进行sort

>>> x
[('Job 1', '3', '1'), ('Job 2', '1', '3'), ('Job 3', '2', '3'), ('Job 4', '4', '3')]
>>> sorted(x, key=lambda x: (int(x[1]), int(x[2])))
[('Job 2', '1', '3'), ('Job 3', '2', '3'), ('Job 1', '3', '1'), ('Job 4', '4', '3')]
>>> y = _
>>> for i in x:
...   print(i)
... 
('Job 1', '3', '1')
('Job 2', '1', '3')
('Job 3', '2', '3')
('Job 4', '4', '3')
>>> for j in y:
...   print(j)
... 
('Job 2', '1', '3')
('Job 3', '2', '3')
('Job 1', '3', '1')
('Job 4', '4', '3')
>>> 

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

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