迭代元组列表

2024-04-26 10:17:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种干净的方法来遍历元组列表,其中每个元组都是一对,如so[(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)

Tags: to方法in列表fordata标准len
3条回答

以下是一些想法:

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 ]

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

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]

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

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

相关问题 更多 >