Modifying all the tuples in a Python list

余生长醉 提交于 2019-12-02 10:33:04

问题


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?


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/16329601/modifying-all-the-tuples-in-a-python-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!