简体   繁体   中英

Compare two list of tuples to create a new tuple containing highest values

I have the following code which will compare the two dictionaries b and c and create a third one from them called d which contains the product of comparing b to c and taking the highest one:

b = {1:0,2:0,3:0,4:0,5:0}
c = {1:1,4:4,5:5}

d={k:c[k] if k in c and c[k]>b[k] else v for k,v in b.items()}

However, because dictionaries are not sorted I have had to use the following syntax to convert b and c into tuples, before comparing them, so that they are in the right order:

b = sorted(b.iteritems()) 
c = sorted(c.iteritems()) 

This produces an output of:

b = [(1,0),(2,0),(3,0),(4,0),(5,0)]
c = [(1,1),(4,4),(5,5)]

However I am now unsure of how I could compare the two tuples and produce an output that looks like this:

d = [(1,1),(2,0),(3,0),(4,4),(5,5)]

There does not seem to be a tuple comprehension available in Python 2.7, unless I have not been looking for answers in the right places.

Can anyone assist?

Why can't you just sort the items of d ?

b = {1:0, 2:0, 3:0, 4:0, 5:0}
c = {1:1, 4:4, 5:5}

d = {k: c[k] if k in c and c[k] > b[k] else v for k, v in b.items()}
sorted(d.items())

I suppose this implies that you know the keys of c are a subset of the keys in b . If this isn't true, you need to get the union of the keys and them compare the values from each dict:

b = {1:0, 2:0, 3:0, 5:0}
c = {1:1, 4:4, 5:5}  # note, 4 not in "b"
ninf = -float('inf')  # some value smaller than all others.
all_keys = b.viewkeys() | c  # Union of keys.
result = [(k, max(b.get(k, ninf), c.get(k, ninf))) for k in sorted(all_keys)]
print(result)  # [(1, 1), (2, 0), (3, 0), (4, 4), (5, 5)]

You can add a one liner (the last line) to the upper code snippet:

b = {1:0,2:0,3:0,4:0,5:0}
c = {1:1,4:4,5:5}

d={k:c[k] if k in c and c[k]>b[k] else v for k,v in b.items()}
print [(k, v) for k, v in d.items()] # [(1, 1), (2, 0), (3, 0), (4, 4), (5, 5)]

You can do the same thing, but in the order of the sorted keys of b, and make a tuple on the fly

d=tuple( 
     (k  ,  (c[k] if k in c and c[k]>b[k] else b[k])  ) 
          for k in sorted(b.keys()) )

or some might prefer

d=tuple( 
     (k  ,  max(b[k],c.get(k,minus_inf))  ) 
          for k in sorted(b.keys()) )

... if a suitable minus_inf exists which is less than all possible b[k]. For numbers, None works so you could use

d=tuple( 
     (k  ,  max(b[k],c.get(k))  )   # note, max( x,None)==x  here 
                  for k in sorted(b.keys()) )

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