繁体   English   中英

使用内部列表中的特定变量对列表列表进行排序

[英]sort list of lists using a specific variable from inner list

我正在对文件进行一些操作并将其行转换为列表

l1 = [
    ['john', 'age', '23', 'has', 'scored', '90,'],
    ['sam', 'scored', '70,', 'and', 'age', 'is', '19,'],
    ['rick', 'failed', 'as' ,'he', 'scored', '20,'],
]

如我们所见,并非所有列表/行都相似,但是很常见的是整数后跟单词'scored' 有没有一种方法可以根据关键字'scored'后面的整数进行排序?

早些时候,我尝试了以下类似的列表,但它确实起作用,但这对上面的列表没有帮助

sorted(l1, key=lambda l: int(l[4].rstrip(',')),reverse=True)

这是一种方法:

>>> a_list = [['john', 'age', '23', 'has', 'scored', '90,'], 
['sam', 'scored', '70,', 'and', 'age', 'is', '19,'], 
['rick', 'failed', 'as', 'he', 'scored', '20,']]

>>> sorted(a_list, key = lambda l: int(l[l.index('scored') + 1].strip(",")), reverse=True)

[['john', 'age', '23', 'has', 'scored', '90,'], 
 ['sam', 'scored', '70,', 'and', 'age', 'is', '19,'], 
 ['rick', 'failed', 'as', 'he', 'scored', '20,']]

暂无
暂无

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

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