How to compare an item within a list of list in python

2024/11/15 16:25:01

I am a newbie to python and just learning things as I do my project and here I have a list of lists which I need to compare between the second and last column and get the output for the one which has the largest distance. Moreover, I am replicating a list. If someone could help me to do it within a single list of lists in ag it could be really helpful. Thanks in advance

if this is an INPUT then the output should be,

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 wasc= []
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]]
Answer

In short: To compare items in an iterable (e.g. list) of lists, use the keyword agument key of the max/min function. It takes a function or lambda expression and compares the given values by the result of the key function when given each value.


Assuming that what you really want is to reduce a list of lists so that the entries' second elements are unique and that you want the last elements to determin which entry to keep in case of redundant 2nd values:

If there is any problem regarding iteration, itertools has the answer. In this case, we just need the groupby method and standard Python's max method with the keyword argument key.

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

We could squeeze this into a single generator expression or list comprehension but for a beginner, the above code should be complex enought.

Please be sure to follow Stack Overflow's guidelines for future questions to prevent low ratings and ensure prompt and high quality answers.

https://en.xdnf.cn/q/119032.html

Related Q&A

Make for loop execute parallely with Pandas columns

Please convert below code to execute parallel, Here Im trying to map nested dictionary with pandas column values. The below code works perfectly but consumes lot of time. Hence looking to parallelize t…

Pre-calculate Excel formulas when exporting data with python?

The code is pulling and then putting the excel formulas and not the calculated data of the formula. xxtab.write(8, 3, "=H9+I9")When this is read in and stored in that separate file, it is sto…

Validating Tkinter Entry Box

I am trying to validate my entry box, that only accepts floats, digits, and operators (+-, %). But my program only accepts numbers not symbols. I think it is a problem with my conditions or Python Rege…

Imaplib with GMail offsets uids

Im querying my gmail inbox using pythons ImapLib with a range parameter, but my returned uids are offset from what I request. My request is as follows:M = imaplib.IMAP4_SSL(imap.gmail.com) M.login(USER…

Accessing a folder containing .wav files [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…

What is the right Python idiom for sorting by a single criterion (field or key)? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 8…

Incorrect checking of fields in list using a for loop

I have the following code that seeks to read the file contents into a list (this bit works) and then display a message of acceptance, IF the bank details (user and corresponding number) matches. e.g. i…

Why myVar = strings.Fields(scanner.Text()) take much more time than comparable operation in python?

Consider the following code in golangnow := time.Now() sec1 := now.Unix()file, err := os.Open(file_name) if err != nil {log.Fatal(err) } defer file.Close()scanner := bufio.NewScanner(file)var parsedLin…

When reading an excel file in Python can we know which column/field is filtered

I want to capture the field or column name that is filtered in the excel file when reading through python. I saw that we can also capture only the filtered rows by using openpyxl and using hidden == Fa…

Error:__init__() missing 1 required positional argument: rec

I am new to python. I am trying to do microphone file that ought to detect, listen, record and write the .wav files. However, it is giving me an error while I am trying to run the file. It is saying:Ty…