substitution of list elements

A

antar2

I want to replace each first element in list 5 that is equal to the
first element of the list of lists4 by the fourth element. I wrote
following code that does not work:

list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q',
'f']]
list5 = ['1', '2', '3']

for j in list4:
for k in list5:
if j[0] == k:
k = j[3]
print list5
Wanted result: ['c', 'e', '3']

thanks!
 
W

Wolfram Kraus

I want to replace each first element in list 5 that is equal to the
first element of the list of lists4 by the fourth element. I wrote
following code that does not work:

list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q',
'f']]
list5 = ['1', '2', '3']

for j in list4:
for k in list5:
for i,k in enumerate(list5):
if j[0] == k:
k = j[3]
list5 = j[3]
print list5
Wanted result: ['c', 'e', '3']

thanks!

You didn't replace the list element itself.

HTH,
Wolfram
 
B

bruno.desthuilliers

I want to replace each first element in list 5 that is equal to the
first element of the list of lists4 by the fourth element. I wrote
following code that does not work:

list4 = [['1', 'a', 'b', 'c'], ['2', 'd', 't', 'e'], ['8', 'g', 'q',
'f']]
list5 = ['1', '2', '3']

for j in list4:
for k in list5:
if j[0] == k:
k = j[3]
print list5
Wanted result: ['c', 'e', '3']

thanks!

select = lambda item, lst: (item, lst[3])[item == lst[0]]
list5[:] = [select(*pair) for pair in zip(list5, list4)]

# or if you prefer a more procedural solution:

for index, (item, lst) in enumerate(zip(list5, list4)):
if item == lst[0]:
list5[index] = lst[3]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top