[英]iterating over a list comprehension in python
Why does when I run : 为什么当我跑步时:
a = ['a','n','g']
b = [range(0,4)]
print [(x,y) for x in a for y in b]
returns : 返回:
[('a', [0, 1, 2, 3]), ('n', [0, 1, 2, 3]), ('g', [0, 1, 2, 3])]
but when I run this piece of code: 但是当我运行这段代码时:
a = ['a','n','g']
b = [0,1,2,3,4]
print [(x,y) for x in a for y in b]
It returns: 它返回:
[('a', 0), ('a', 1), ('a', 2), ('a', 3), ('a', 4), ('n', 0), ('n', 1), ('n', 2), ('n', 3), ('n', 4), ('g', 0), ('g', 1), ('g', 2), ('g', 3), ('g', 4)]
So as you may have noticed, if I use the range function, I get a wrong output but If I manually key in ['a','n','g'] I get the desired output 因此,您可能已经注意到,如果我使用范围函数,则会得到错误的输出,但是如果手动键入['a','n','g'] ,则会得到所需的输出
b = [range(0,4)]
and
b = [0,1,2,3,4]
Both are obviously the same right? 两者显然是对的吗? therefore why do there results vary (if they are the same) ?
因此,为什么结果会有所不同(如果它们相同) ?
I'm basically trying to build a program which has A in a range of 999 reversed and B with a range of 999 and believe me hard coding those 1000 digits is not efficient and I might probably be considered insane 我基本上是在尝试构建一个程序,该程序的A的取值范围为999, B的取值范围为999,并且我认为对这1000位数字进行硬编码效率不高,我可能会觉得很疯狂
[range(0,4)]
is the same as [[0,1,2,3]]
, so it is very much not the same as [0,1,2,3,4]
. [range(0,4)]
与[[0,1,2,3]]
,因此与[0,1,2,3,4]
几乎不相同。
I think you just want range(0,5)
(note that there are no square brackets around this, and to include 4
in the result you need to have 5
for the stop
argument of range()
). 我认为您只需要
range(0,5)
(请注意,这周围没有方括号,并且要在结果中包含4
,您需要对range()
的stop
参数使用5
)。
And for your specific problem: "I'm basically trying to build a program which has A
in a range of 999 reversed and B
with a range of 999": 针对您的特定问题:“我基本上是在尝试构建一个程序,该程序的
A
取反范围为999, B
反范围为999”:
A = range(999, -1, -1)
B = range(1000)
This assumes that you want ranges like [999, 998, ..., 1, 0]
and [0, 1, ..., 998, 999]
. 假设您要使用
[999, 998, ..., 1, 0]
和[0, 1, ..., 998, 999]
。
Both are obviously the same right?
两者显然是对的吗?
>>> [1, 2, 3, 4]
[1, 2, 3, 4]
>>> [range(0,4)]
[[0, 1, 2, 3]]
The two are not the same; 两者是不一样的。 you probably meant
b = range(0,4)
without the extra set of brackets. 您可能是说
b = range(0,4)
而没有多余的括号。
No, these two are not the same. 不,这两个不一样。 You can think of
你可以想到
[range(0, 4)]
as this 这样
[[0, 1, 2, 3]]
Note it is a list of lists. 请注意,这是一个列表列表。
So when you are doing a list comprehension over this list, it will simply iterate over the single element [0, 1, 2, 3]
over and over again. 因此,当您对该列表进行列表理解时,它将简单地反复遍历单个元素
[0, 1, 2, 3]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.