Iterate to the end of the second array using python

I did something like this:

d = [('e', 0), ('f', 1), ('e', 0), ('f', 1)]
e = ['a']
d = [(n,j) for n,(i,j) in zip(e,d)]
d
[('a',0)]

I just tried replacing the equivalent tuple value with an array value without changing the related numbers. But the list goes only to the len array e, not d. What I want to get as output looks something like this:

d
[('a', 0), ('f', 1), ('e', 0), ('f', 1)]
+4
source share
4 answers

Just add the raw tail dto the machined part:

[(n,j) for n,(i,j) in zip(e,d)] + d[len(e):]
#[('a', 0), ('f', 1), ('e', 0), ('f', 1)]
+4
source

You can use itertools.zip_longest:

[(n or i, j) for n,(i,j) in itertools.zip_longest(e, d)]

Tick doc

+3
source

d, d, e:

d = [('e', 0), ('f', 1), ('e', 0), ('f', 1)]
e = ['a']

for i, new_letter in enumerate(e):
    d[i] = (new_letter, d[i][1])

print(d)
# [('a', 0), ('f', 1), ('e', 0), ('f', 1)]

, Python . d[i][0] = new_letter :

TypeError: 'tuple'

The above code changes the list dinto place, replacing the old tuples with new ones. He cannot change old tuples.

+1
source

I think the problem is in the zip function. The documentation says that (zip) "Returns the tuple iterator, where the i-th tuple contains the i-th element from each of the sequences of arguments or iterations. The iterator stops when the shortest input iterable is exhausted."

[(n,j) for n,(i,j) in zip(e,d)] + d[len(e):] gotta do the trick

0
source

Source: https://habr.com/ru/post/1682817/


All Articles