简体   繁体   中英

Add tuple to a list of tuples

How can I sum a tuple to a list of tuples such as:

>>> a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> b = (10, 20, 30)

the result being:

>>> c 
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

I know this can be easily solved with numpy:

>>> import numpy
>>> c = numpy.add(a, b).tolist()
>>> c
[[10, 21, 32], [13, 24, 35], [16, 27, 38]]

but I'd rather avoid numpy.

one-liner using nested list comprehensions and the magic zip to interleave the fixed b triplet to add to the iterating element of a , no numpy needed:

a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
b = (10, 20, 30)

c = [tuple([i+j for i,j in zip(e,b)]) for e in a]
print(c)

result:

[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

EDIT: you could drop the tuple conversion if not needed:

c = [[i+j for i,j in zip(e,b)] for e in a]

You can do this with list comprehension:

a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
b = (10, 20, 30)
c = [[x + b[i] for i, x in enumerate(y)] for y in a]

c will be a list of lists, rather than a list of tuples. If that matters, you can do this instead:

c = [tuple(x + b[i] for i, x in enumerate(y)) for y in a]

Define a function to sum two vectors:

def sum_vectors(a, b):
    return tuple(sum(z) for z in zip(a, b))

Use it to define a function for adding a vector to a list of vectors:

def add_vector_to_vectors(v, ws):
    return [sum_vectors(v, w) for w in ws]

Example usage:

>>> a = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> b = (10, 20, 30)
>>> add_vector_to_vectors(b, a)
[(10, 21, 32), (13, 24, 35), (16, 27, 38)]

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