简体   繁体   中英

Compare elements in a list of lists in python and finding a match

I have a list of lists in Python with each list containing 5 elements. For example

lists = [['x1', 'y1', 'z1', '10', ''],
         ['x1', 'y1', 'z1', '', '5'], 
         ['x2', 'y2', 'z2', '10', ''],
         ['x2', 'y2', 'z2', '10', ''],
         ['x1', 'y1', 'z1', '', '5'],
         ['x3', 'y3', 'z3', '', '40'],
         ['x2', 'y2', 'z2', '', '20']]

I wanted to compare the first 3 elements of each lists and if there is a match, then for the matched lists, I wanted to add the 4th column of every rows and compare it with the sum of 5th column of matched lists. I will need to output the rows if there is a match in the sum of 4th and 5th columns in the set of matched lists.

So in the above example, output should be

output = [['x1', 'y1', 'z1', '10', '10'],
          ['x2', 'y2', 'z2', '20', '20']]           

Can someone provide a solution for this.

Thanks

A one-line solution!

output = [l[:4] + [str(sum(int(j[4]) for j in lists if j[:3] == l[:3] and j[4]))] for l in (l for l in lists if l[3])]

which gives output as:

[['x1', 'y1', 'z1', '10', '10'], ['x2', 'y2', 'z2', '20', '20']]

Instead of trying to explain that line, I have expanded the process into a larger for-loop Scroll down for a proper explanation of how it is working.

output = []
for l in (l for l in lists if l[3]):
    sm = 0
    for j in lists:
         if j[:3] == l[:3] and j[4]:
              sm += int(j[4])
    sm = str(sm)
    if sm == l[3]:
        output.append(l[:4] + [sm])

how?

Well, we are looping through the lists in the generator: l for l in lists if l[3] . Essentially, we just want to start looping through the lists that actually have a value in the third index so that we can sum up the other lists which have the same first three elements and compare this to l[3] .

We then declare a sum variable ( sm ) as 0 which we will add the other lists elements to.

Next we want to begin looping through the other lists in lists which may have the same first three elements.

We then check if the first three elements are the same ( j[:3] == l[:3] ) and also check if there is actually something to add to the sum in the fourth element (otherwise we will get an error when trying to convert an empty string to an int ). Then, if it passes this test, we add j[4] to sm and continue onto the next list.

Next we convert the sum ( sm ) to a string since that is the data type it needs to be in the end and saves converting l[3] to an integer.

Finally we compare this string to the fourth element in our original list - if it is the same, then we append the original list along with the sum (using list concatenation) to the output list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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