Python 迭代元组列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14880192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:44:07  来源:igfitidea点击:

Iterate a list of tuples

pythonlistiterationtuples

提问by Clev3r

I'm looking for a clean way to iterate over a list of tuples where each is a pair like so [(a, b), (c,d) ...]. On top of that I would like to alter the tuples in the list.

我正在寻找一种干净的方法来迭代一个元组列表,其中每个元组都是这样的一对[(a, b), (c,d) ...]。最重要的是,我想更改列表中的元组。

Standard practice is to avoid changing a list while also iterating through it, so what should I do? Here's what I kind of want:

标准做法是在迭代列表的同时避免更改列表,那么我该怎么办?这是我想要的:

for i in range(len(tuple_list)):
  a, b = tuple_list[i]
  # update b's data
  # update tuple_list[i] to be (a, newB)

采纳答案by Martijn Pieters

Just replace the tuples in the list; you canalter a list while looping over it, as long as you avoid adding or removing elements:

只需替换列表中的元组;您可以在循环时更改列表,只要您避免添加或删除元素:

for i, (a, b) in enumerate(tuple_list):
    new_b = some_process(b)
    tuple_list[i] = (a, new_b)

or, if you can summarize the changes to binto a function as I did above, use a list comprehension:

或者,如果您可以b像我上面所做的那样将更改总结为一个函数,请使用列表理解:

tuple_list = [(a, some_process(b)) for (a, b) in tuple_list]

回答by Udo Klein

Why don't you go for a list comprehension instead of altering it?

你为什么不去进行列表理解而不是改变它?

new_list = [(a,new_b) for a,b in tuple_list]

回答by Jonathan Vanasco

here are some ideas:

这里有一些想法:

def f1(element):
    return element

def f2(a_tuple):
    return tuple(a_tuple[0],a_tuple[1])

newlist= []
for i in existing_list_of_tuples :
    newlist.append( tuple( f1(i[0]) , f(i1[1]))

newlist = [ f2(i) for i in existing_list_of_tuples ]