简体   繁体   中英

Modifying Python 3.6.4 list elements

So I have 2 lists:

L1 = ['a', 'b', 'c', 'd']
L2 = ['1', '2', '3', '4']

I need my result to look like this:

['a1', 'b2', 'c3', 'd4']

I used a for loop, but I can't seem to get it right. This is what I did:

L3 = []
L1 = ['a', 'b', 'c', 'd']
L2 = ['1', '2', '3', '4']
for i in range(len(L1)):
     L3 += L1[i] + L2[i]
print(L3)

My results end up looking like:

['a', '1', 'b', '2', 'c', '3', 'd', '4']

And that's all I have. Any help would be greatly appreciated!

The zip function produces an iterator that returns tuples from each of its arguments in sequence:

L3 = [x + y for x, y in zip(L1, L2)]

Documentation: https://docs.python.org/3/library/functions.html#zip

L3 += L1[i] + L2[i] is equivalent to L3.extend(L1[i] + L2[i])

L1[i] + L2[i] is a string like 'a1'. extend expects an iterable, and it will append each of its elements to the list. So, it iterates over your 'a1' string and appends to the list the elements 'a' and '1'.

You want to append the string instead:

L3.append(L1[i] + L2[i])

As noted by Mark Tolonen,

L3 += [L1[i] + L2[i]]

also works. It is equivalent to L3.extend([L1[i] + L2[i]]) , so for example L3.extend(['a1']) . In this case, extend will append the only element of the list it receives as parameter, 'a1', to L3.

You can just change the += operation to .append :

for i in range(len(L1)):
    L3.append(L1[i] + L2[i])
L3 = []
L1 = ['a', 'b', 'c', 'd']
L2 = ['1', '2', '3', '4']
for i in range(len(L1)):
     L3.append(str(L1[i])+str(L2[i]))
print(L3)

与使用列表理解的另一个答案类似:

L3 = [L1[i]+L2[i] for i in range(len(L1))]

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