substitution of list elements

bruno.desthuilliers at gmail.com bruno.desthuilliers at gmail.com
Fri Jul 18 10:13:41 EDT 2008


On 18 juil, 14:33, antar2 <desoth... at yahoo.com> wrote:
> 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]



More information about the Python-list mailing list