Python for 循环中的列表初始化

发布于 2024-10-14 06:51:08 字数 294 浏览 3 评论 0原文

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

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

不幸的是,即使我想要它,这个循环也不会改变 list_x 。

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

我意识到我可以使用列表理解,但是当for循环非常复杂时,这很难阅读。

编辑:我的 for 循环有 20 行。您通常会将 20 行放入一个列表推导式中吗?

How do initialize a list in a for loop:

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

unfortunately, this loop does not alter list_x even though I want it to.

Is there a way to have references to the elements of list_x in the loop?

I realize I could use a list comprehension, but that's hard to read when the for loop is very complicated.

Edit: My for loop is 20 lines. Would you normally put 20 lines into a single list comprehension?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆萌少年 2024-10-21 06:51:08

为什么列表理解会很复杂?

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

您可以使用一组生成器表达式或将代码子集抽象为 f 函数,而不是使用 20 行 for 循环。

在看不到代码的情况下讨论可以做什么确实毫无意义。

why would list-comprehension be complicated?

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

Instead of having 20-line for loop, you could use a set of generator expressions or abstract a subset of code into an f function.

It's really is pointless to talk about what could be done w/o seeing the code.

离线来电— 2024-10-21 06:51:08

这能行吗?

# 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

Would this do it?

# 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
十年不长 2024-10-21 06:51:08

这也只是一个穷人的冗长列表理解。

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 ) )

This is just a poor man's verbose list comprehension, also.

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 ) )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文