如何在python中的列表列表中比较项目

时间:2019-07-02 08:31:25

标签: python

我是python的新手,在做项目时会学习一些东西,这里有一个列表列表,我需要在第二列和最后一列之间进行比较,以获取距离最大的列表的输出。而且,我正在复制一个列表。如果有人可以帮我在列表中的一个列表中做到这一点,那将真的很有帮助。 预先感谢

如果这是输入,则输出应为

ag = [['chr12','XX',1,5,4],
     ['chr12','XX',2,5,3],
     ['chr13','ZZ',6,10,4],
     ['chr13','ZZ',8,9,1],
     ['ch14','YY',12,15,3],['ch14','YY',12,15,3]]

EXPECTED OUTPUT:

     ['chr12','XX',1,5,4]
     ['chr13','ZZ',6,10,4]
     ['ch14','YY',12,15,3]

#However I tried of replicating the list like
#INPUT
ag = 
 [['chr12','XX',1,5,4],
 ['chr12','XX',2,5,3],
 ['chr13','ZZ',6,10,4],
 ['chr13','ZZ',8,9,1],
 ['ch14','YY',12,15,3],
 ['ch14','YY',12,15,3]]
 bg = 
 [['chr12','XX',1,5,4],
 ['chr12','XX',2,5,3],
 ['chr13','ZZ',6,10,4],
 ['chr13','ZZ',8,9,1],
 ['ch14','YY',12,15,3],
 ['ch14','YY',12,15,3]]


#The code which I tried was

c= []
for i in ag:
 for j in bg:
    if i[0]==j[0] and i[1]==j[1] and i[4]>j[4]:
        c.append(i)


the output which i get is
[['chr12', 'XX', 1, 5, 4], ['chr13', 'ZZ', 6, 10, 4]]

2 个答案:

答案 0 :(得分:1)

简而言之:要比较可迭代(例如列表)列表中的项目,请使用max / min函数的关键字参数key。它接受一个函数或lambda表达式,并在给定每个值时将其与key函数的结果进行比较。


假设您真正想要的是减少列表的列表,以便条目的第二个元素是唯一的,并且您希望最后一个元素确定在冗余第二个值的情况下保留哪个条目:

如果有关于迭代的任何问题,itertools就是答案。在这种情况下,我们只需要groupby方法和带有关键字参数key的标准Python的max方法。

from itertools import groupby

def filter(matrix):
    filtered = [] # create a result list to hold the rows (lists) we want
    for key, rows in groupby(matrix, lambda row: row[1]): # get the rows grouped by their 2nd element and iterate over that
        filtered.append(max(rows, key=lambda row: row[-1])) # add the line that among its group has the largest last value to our result
    return filtered # return the result

我们可以将其压缩为单个生成器表达式或列表理解,但是对于初学者来说,以上代码应该足够复杂。

对于以后的问题,请务必遵循Stack Overflow的guidelines,以防止收视率过低并确保给出及时且高质量的答案。

答案 1 :(得分:0)

您的列表agbg是完全重复的,因此我为您的问题提供此示例。希望对您有所帮助。

>>>ag = [['chr12','XX',1,5,4],['chr12','XX',2,5,3],['chr13','ZZ',6,10,4],['chr13','ZZ',8,9,1],['ch14','YY',12,15,3]]
>>>bg = [['chr12','XX',1,5,4],['chr12','XX',2,5,3],['chr13','ZZ',6,10,4],['chr13','ZZ',8,9,1]]
>>>[i for i in ag + bg if i not in ag or i not in bg]
[['ch14', 'YY', 12, 15, 3]]