在for循环中初始化Python列表

3 投票
3 回答
28763 浏览
提问于 2025-04-16 10:40

如何在一个循环中初始化一个列表:

for x, y in zip(list_x, list_y):
     x = f(x, y)

不幸的是,这个循环并没有改变 list_x,尽管我希望它能改变。

有没有办法在循环中引用 list_x 的元素呢?

我知道我可以使用列表推导式,但当循环非常复杂时,这样写就很难读懂。

编辑:我的for循环有20行。你通常会把20行放进一个列表推导式里吗?

3 个回答

3

这其实就是一种简单的、冗长的列表推导方式。

def new_list( list_x, list_y ):
    for x, y in zip(list_x, list_y):
        yield f(x, y)

list_x = list( new_list( list_x, list_y ) )
10

为什么列表推导会让人觉得复杂呢?

list_x[:] = [f(tup) for tup in zip(list_x, list_y)]

与其写20行的循环代码,你可以使用一些生成器表达式,或者把一部分代码抽象成一个f函数。

光说能做什么其实没什么意义,得先看看代码才能明白。

3

这样做可以吗?

# Create a temporary list to hold new x values
result = []

for x, y in zip(list_x, list_y):
     # Populate the new list
     result.append(f(x, y))

# Name your new list same as the old one
list_x = result

撰写回答