nutship
nutship

Reputation: 4924

Comparing values from different tuples, list comprehension

I have two lists of tuples:

old = [('6.454', '11.274', '14')] 
new = [(6.2845306, 11.30587, 13.3138)]

I'd want to compare each value from the same position (6.454 against 6.2845306 and so on) and if value from the old tuple is greater then value from the new tuple, I print it.

The net effect should be then:

6.454, 14 

I did it using simple if statement

if float(old[0][0]) > float(new[0][0]):
    print old[0][0],
if float(old[0][1]) > float(new[0][1]):
    print old[0][1],
if float(old[0][-1]) > float(new[0][-1]):
    print marathon[0][-1]

Since there are always 3 or 2-element tuples, it's not a big problem to use slicing here but I'm looking for more elegant solution, which is list comprehension. Thank you for any help.

Upvotes: 0

Views: 1285

Answers (4)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250911

use the built-in function zip:

for x,y in zip(old[0],new[0]):
    if float(x)>float(y):
        print x,
   ....:         
6.454 14

If the tuples are of unequal length then zip will only compare up to the shorter of the two, you can handle that case using itertools.izip_longest

help on zip:

In [90]: zip?
Type:       builtin_function_or_method
String Form:<built-in function zip>
Namespace:  Python builtin
Docstring:
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences.  The returned list is truncated
in length to the length of the shortest argument sequence.

Upvotes: 2

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

Try this:

for i in range(len(old)):
    for j in range(len(old[i]):
        if old[i][j]>new[i][j]:
            print old[i][j]

Upvotes: 1

Alexander Kuzmin
Alexander Kuzmin

Reputation: 1120

[o for o,n in zip(old[0], new[0]) if float(o) > float(n)]

This should work?

Upvotes: 2

mgilson
mgilson

Reputation: 309881

So you want something like:

print [o for o,n in zip(old[0],new[0]) if float(o) > float(n)]

Upvotes: 2

Related Questions