简体   繁体   English

Python:按字母顺序对列表列表进行排序/分组

[英]Python: sorting/grouping lists of lists alphabetically

I feel like this has already been asked, but the answers for the questions have not worked for my code. 我觉得已经有人问过了,但是问题的答案对我的代码不起作用。

I am trying to sort a list of lists alphabetically based on first list[2] then within matching entries sorted by list[3] and then list[4] and so on. 我正在尝试根据第一个list [2]按字母顺序对列表列表进行排序,然后在按list [3],然后按list [4]排序的匹配条目内进行排序。 The real data is bigger and has more entries in each list but an example: 实际数据更大,并且每个列表中都有更多条目,但有一个示例:

list = [ 
['X_campestris_vesicatoria', 'Bacteria', 'Proteobacteria',
   'Gammaproteobacteria', 'Xanthomonadales', 'Xanthomonadaceae', 'Xanthomonas'],
['Pantoea', 'Bacteria', 'Proteobacteria', 'Gammaproteobacteria',
   'Enterobacteriales', 'Enterobacteriaceae', 'Pantoea'],
['Acidobacterium', 'Bacteria', 'Acidobacteria', 'Acidobacteriales',
   'Acidobacteriaceae', 'Granulicella'],
['S_boydii', 'Bacteria', 'Proteobacteria', 'Gammaproteobacteria',
   'Enterobacteriales', 'Enterobacteriaceae', 'Shigella']]

I have tried some of the things that similar questions have as answers: 我已经尝试过类似问题作为答案的一些事情:

taxlist.sort(key = lambda row: (row[2],row[3],row[4],row[5]))
print taxlist

but no sorting is happening. 但没有排序。

same with when I try: 与我尝试时相同:

sorted(taxlist, key=lambda x: (x[2],x[3],x[4],x[5]))
print taxlist

And once the list is sorted can I still use this or is the list no longer iterable? 列表排序后,我是否仍可以使用它,或者列表不再可迭代?

import csv
writer = csv.writer(sys.stdout, delimiter="\t")
writer.writerows(taxlist)

Thanks for any help. 谢谢你的帮助。

sorted gives you a new list, while L.sort sorts L in place. sorted给您一个新列表,而L.sort L进行适当排序。 In both cases, the original list is still accessible and can be iterated over. 在这两种情况下,原始列表仍然可以访问并且可以迭代。

In the even that you use sorted , the old list is still accessible and can be iterated over. 即使您使用sorted ,仍然可以访问旧列表并可以对其进行迭代。 The list that is returned is also accessible and can be iterated over. 返回的列表也可以访问,并且可以对其进行迭代。

Hope that helps 希望能有所帮助

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

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