【发布时间】:2021-01-11 08:41:21
【问题描述】:
为什么会这样?我越来越糊涂了。
在第一种情况下,我通过列表理解来定义chunked_test_list。输出符合预期。
但是,在下一个案例中,我将chunked_test_list 定义为生成器。然后,当我用 for 循环查看它时,只有第一个循环给了我预期的结果,其余的是 EMPTY 列表。我很困惑..
而且,在最后一种情况下,我在 for 循环中将变量名从 test_list 更改为 test_list_1,然后结果按预期运行。哦,我更糊涂了。
test_list = [1, 2, 3, 4, 5, 6, 7, 8]
step = 2
chunked_test_list = [test_list[x: x + step] for x in range(0, len(test_list), step)]
for test_list in chunked_test_list:
print('test_list', test_list)
# >>>output
# test_list [1, 2]
# test_list [3, 4]
# test_list [5, 6]
# test_list [7, 8]
test_list = [1, 2, 3, 4, 5, 6, 7, 8]
step = 2
chunked_test_list = (test_list[x: x + step] for x in range(0, len(test_list), step)) # GENERATOR
for test_list in chunked_test_list: # the variable name `test_list` is SAME to list above
print('test_list', test_list)
# >>>output
# test_list [1, 2]
# test_list []
# test_list []
# test_list []
test_list = [1, 2, 3, 4, 5, 6, 7, 8]
step = 2
chunked_test_list = (test_list[x: x + step] for x in range(0, len(test_list), step)) # GENERATOR
for test_list_1 in chunked_test_list: # the variable name `test_list` is NOT same to list above
print('test_list_1', test_list_1)
# >>>output
# test_list_1 [1, 2]
# test_list_1 [3, 4]
# test_list_1 [5, 6]
# test_list_1 [7, 8]
【问题讨论】:
-
您对初始列表和循环变量使用相同的变量名称 (
test_list)。如果在循环中使用不同的变量名,它可以正常工作。 -
是的。但是如果我使用列表而不是生成器,它会打印出预期的结果,即使变量名相同。你能解释一下为什么吗?
-
如果您一次运行所有这些,那么您正在尝试使用 test_list 制作生成器,这不是您定义的那个,而是上一个循环中列表的最后一个元素。 .just 使用不同的变量名,这看起来是不好的做法 - 显然会导致你出错
-
在 for 循环中使用列表时,初始顺序在循环开始时确定。更新基础列表没有影响。使用迭代器时,循环中的下一个元素在每次迭代时确定,因此在循环时更改底层列表确实会产生影响。
-
@Mike67 所说的
标签: python scope namespaces generator