问题描述
我正在寻找一种干净的方法来遍历一个元组列表,其中每个都是一对,如此 [(a,b),(c,d)...]
。最重要的是,我想改变列表中的元组。
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.
标准做法是避免更改列表同时迭代它,所以我该怎么办?这就是我想要的:
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)
推荐答案
只需替换列表中的元组即可;只要您避免添加或删除元素,可以在循环时修改列表:
Just replace the tuples in the list; you can alter 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)
或者,如果您可以将对 b
的更改汇总到我上面所做的函数中,请使用列表理解:
or, if you can summarize the changes to b
into a function as I did above, use a list comprehension:
tuple_list = [(a, some_process(b)) for (a, b) in tuple_list]
这篇关于迭代元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!