Python 迭代元组列表

Python 迭代元组列表,python,list,iteration,tuples,Python,List,Iteration,Tuples,我正在寻找一种干净的方法来迭代元组列表,其中每个元组都是一对,就像这样[(a,b),(c,d)…]。最重要的是,我想改变列表中的元组 标准做法是避免在遍历列表时更改列表,所以我应该怎么做?以下是我想要的: for i in range(len(tuple_list)): a, b = tuple_list[i] # update b's data # update tuple_list[i] to be (a, newB) 你为什么不去做一个列表而不是修改它呢 new_list =

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

标准做法是避免在遍历列表时更改列表,所以我应该怎么做?以下是我想要的:

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

你为什么不去做一个列表而不是修改它呢

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

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

for i, (a, b) in enumerate(tuple_list):
    new_b = some_process(b)
    tuple_list[i] = (a, new_b)
或者,如果您可以像上面那样将对
b
的更改汇总到一个函数中,请使用列表:

tuple_list = [(a, some_process(b)) for (a, b) in tuple_list]
以下是一些想法:

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 ]

嗯,你并不是真的用这个来更新列表,你只是在更新元组。对,所以像
tuple\u list[i]=(a,newB)
。。。除非我想避免在循环中这样做。我很好奇是否有更干净的方法。@claire:你给出的循环很好;它不会遍历正在更新的列表,而只是遍历索引。这是处理列表的一种完全标准的方法,只要您不更改列表中的元素数量(您没有更改)。为什么要使用
元组(…)
,而只要
(…)
就可以了?只是为了更具可读性。这里有很多括号,我不觉得这样更可读;相反,它会分散我的注意力,让我觉得你是在将另一个序列类型转换为元组。我同意你的
f2
函数。但是在append函数中
newlist.append(元组(f1(i[0]),f(i1[1]))
vs
newlist.append((f1(i[0]),f(i1[1]))
。我发现前者更具可读性。