[英]List Comprehension - Double Loop or Not?
I am having the following issue: 我遇到以下问题:
# Neither this
trial1 = [[x for x in 10000 // 5**i] for i in range(1, 10)]
# nor this
trial2 = [x for i in range(1, 10) for x in 10000 // 5**i]
# work.
They both return: "int" object is not iterable, which is somehow confusing to me. 它们都返回:“ int”对象是不可迭代的,这在某种程度上使我感到困惑。 Since i
is an array (1,2,3,...,9)
so must be the 10000 // 5**i
formula. 由于i
是一个数组(1,2,3,...,9)
因此必须是10000 // 5**i
公式。 So which is the integer i
can't iterate over?. 那i
不能迭代哪个整数? I want trial
to be a list containing all these values. 我希望trial
是包含所有这些值的列表。
How is this so different? 这有何不同?
trial = []
for i in range(1, k):
trial.append(10000 // 5**i)
How does one go about formulating the list comprehension statement? 如何制定列表理解语句?
The comprehension equivalent of your working for
loop would be: 与for
循环等效的理解for
:
[10000 // 5**i for i in range(1, 10)]
There are no double loops in that example, so there shouldn't be in the comprehension either. 该示例中没有双循环,因此也不应该包含任何理解。
Regarding your second question; 关于第二个问题; i
is not a list with values (0, 1, ... , 9)
but it is a single integer out of that list. i
不是一个值(0, 1, ... , 9)
的列表,但它是该列表之外的一个整数。
The equivalent of 相当于
trial = []
for i in range(1, k):
trial.append(n // 5**i)
is simply 很简单
trial = [10000 // 5**i for i in range(1, k)]
since you are simply calculating 10000 // 5**i
for ever i
in range(1, k)
因为你只是计算10000 // 5**i
永远i
在range(1, k)
for x in 10000 // 34**i
or anything like that means iterating through a number , which doesn't make sense and results in an error. for x in 10000 // 34**i
或类似的东西意味着迭代一个数字 ,这没有意义,并导致错误。
You seem to be trying to append numbers to a list, which is easy: 您似乎正在尝试将数字追加到列表中,这很简单:
trial = [10000 // 5**i for i in range(1, 5)]
Here you're basically saying: 在这里,您基本上是在说:
[...]
) 创建列表( [...]
) 10000//5**i
由值组成,每个值等于10000//5**i
i
is every number from range(1, 5)
i
是range(1, 5)
每个数字
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.