简体   繁体   中英

Modifying all the tuples in a Python list

I have a list containing tuples with a standard format:

bar_list = [(bar1, bar2, bar3, bar4), (bar1, bar2, bar3, bar4), (bar1, bar2, bar3, bar4)...] 

Though I want to iterate through each tuple in the list and for each make specific modifications such as:

foo0 = bar1
foo1 = get_foo(foo0) #get_foo(var) being a function
foo2 = bar2
foo3 = bar3/2

And then repackage the revalued tuples in another list:

foo_list = [(foo1, foo2, foo3), (foo1, foo2, foo3), (foo1, foo2, foo3)...]

How could I accomplish this?

You could use a list comprehension :

foo_list = [(get_foo(bar1), bar2, bar3/2) 
            for bar1, bar2, bar3, bar4 in bar_list]

Note, I'm assuming you meant for foo1 to equal get_foo(bar1) rather than the NameError -raising and self-referential

foo1 = get_foo(foo1)

You could use map here:

def func(lis):
    bar1,bar2,bar3,bar4=lis
    foo0 = bar1
    foo1 = get_foo(foo0) #or get_foo(bar1)
    foo2 = bar2
    foo3 = bar3/2
    return foo1,foo2,foo3


bar_list = [(bar1, bar2, bar3, bar4), (bar1, bar2, bar3, bar4), (bar1, bar2, bar3, bar4)...] 

foo_list = map(func,bar_lis)

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