[英]Python: generating tuples in a list
Is there an elegant/alternative way to do this: 是否有一种优雅/替代的方式来做到这一点:
allcolors = []
for Red in range(0,256):
for Green in range(0,256):
for Blue in range(0,256):
allcolors.append((Red,Green,Blue))
I was thinking something like (Pseudo code) : 我在想类似(伪代码)的东西:
[Red for Red in [Green for Green in [Blue for Blue in range(0,256)]]]
This will work: 这将起作用:
allcolors = [(Red,Green,Blue) for Red in range(0,256) for Green in range(0,256) for Blue in range(0,256)]
In list comprehensions , the for ... in ...
clauses go in the same order as if they were for-loops. 在列表推导中 , for ... in ...
子句的顺序与它们作为for循环的顺序相同。
Secondly, the 0's passed to range
are redundant here since range
starts at 0 by default. 其次,此处传递给range
的0是多余的,因为默认情况下range
从0开始。 In other words, you can write the same thing more consicely like so: 换句话说,您可以更简洁地编写相同的内容,如下所示:
allcolors = [(Red,Green,Blue) for Red in range(256) for Green in range(256) for Blue in range(256)]
Also, if you are on Python 2.x, you should use xrange
instead of range
: 另外,如果您使用的是Python 2.x,则应使用xrange
而不是range
:
allcolors = [(Red,Green,Blue) for Red in xrange(256) for Green in xrange(256) for Blue in xrange(256)]
This is because xrange
returns an iterator instead of constructing an unnecessary list like range
. 这是因为xrange
返回迭代器,而不是构造不必要的列表(例如range
。
Finally, the convention for Python variable names is that they be lowercase. 最后,Python变量名称的约定是小写。 Meaning, Red
, Green
, and Blue
should be named red
, green
, and blue
. 含义, Red
, Green
和Blue
应分别命名为red
, green
和blue
。 :) :)
您可以尝试使用列表理解 :
allcolors = [(r, g, b) for r in xrange(0, 256) for g in xrange(0, 256) for b in xrange(0, 256)]
Something like this: 像这样:
allcolors = [ (Red,Green,Blue) for Red in range(0,256) for Green in range(0,256) for Blue in range(0,256) ]
You can transform your loop into a list comprehension by thinking about it like this: 您可以这样考虑循环,从而将循环转换为列表理解:
[(Red,Green,Blue) for Red in range(0,256)
for Green in range(0,256)
for Blue in range(0,256) ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.