[英]Python sorting 2D array by the first element (not unique)
I have a very big 2D array where the second elements are not unique. 我有一个很大的2D数组,其中第二个元素不是唯一的。 Something like this: 像这样:
list = [ ['text43','value43'],
['text23','value23'],
['text12','value12'],
['text43','different_val_43'],
['text12','another_value12'],
['text04','value04'],
['text43','anohter_value43'] ]
I would like to sort it by the first element but not in alphabetical order, just in the order of appearance of first element. 我想按第一个元素进行排序,但不按字母顺序排序,仅按第一个元素的出现顺序排序。 Desired output: 所需的输出:
list = [ ['text43','value43'],
['text43','different_val_43'],
['text43','anohter_value43'],
['text23','value23'],
['text12','value12'],
['text12','another_value12'],
['text04','value04'] ]
You can use a custom sorting function that would return the index at which the first element of a sublist is first found, eg: 您可以使用自定义排序函数 ,该函数将返回在第一次找到子列表的第一个元素时所处的索引,例如:
lst = [['text43','value43'],
['text23','value23'],
['text12','value12'],
['text43','different_val_43'],
['text12','another_value12'],
['text04','value04'],
['text43','anohter_value43']]
d = {}
for i, item in enumerate(lst):
if item[0] not in d:
d[item[0]] = i
lst.sort(key=lambda item: d[item[0]])
print(lst)
Output: 输出:
[['text43', 'value43'],
['text43', 'different_val_43'],
['text43', 'anohter_value43'],
['text23', 'value23'],
['text12', 'value12'],
['text12', 'another_value12'],
['text04', 'value04']]
Look if this helps. 看看是否有帮助。 Using sorted() 使用sorted()
lst = [ ['text43','value43'],
['text23','value23'],
['text12','value12'],
['text43','different_val_43'],
['text12','another_value12'],
['text04','value04'],
['text43','anohter_value43'] ]
sorted(lst, reverse=True)
Output: 输出:
[['text43', 'value43'],
['text43', 'different_val_43'],
['text43', 'anohter_value43'],
['text23', 'value23'],
['text12', 'value12'],
['text12', 'another_value12'],
['text04', 'value04']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.