[英]List of tuples with a certain pattern
Is there a way to create a list of tuples with a certain pattern?有没有办法创建具有特定模式的元组列表? I want to have the following list without having to manually write them all, I think it may be "easy" since there is kind of a pattern in the tuple list, but not sure how to do it.我想拥有以下列表而不必手动编写它们,我认为这可能很“容易”,因为元组列表中有一种模式,但不知道该怎么做。
a = [
[(30, 5, 10),
(30, 5, 20),
(30, 5, 30),
(30, 10, 10),
(30, 10, 20),
(30, 10, 30),
(30, 20, 10),
(30, 20, 20),
(30, 20, 30)],
[(35, 5, 10),
(35, 5, 20),
(35, 5, 30),
(35, 10, 10),
(35, 10, 20),
(35, 10, 30),
(35, 20, 10),
(35, 20, 20),
(35, 20, 30)],
[(40, 5, 10),
(40, 5, 20),
(40, 5, 30),
(40, 10, 10),
(40, 10, 20),
(40, 10, 30),
(40, 20, 10),
(40, 20, 20),
(40, 20, 30)]
]
a
Output: Output:
[[(30, 5, 10),
(30, 5, 20),
(30, 5, 30),
(30, 10, 10),
(30, 10, 20),
(30, 10, 30),
(30, 20, 10),
(30, 20, 20),
(30, 20, 30)],
[(35, 5, 10),
(35, 5, 20),
(35, 5, 30),
(35, 10, 10),
(35, 10, 20),
(35, 10, 30),
(35, 20, 10),
(35, 20, 20),
(35, 20, 30)],
[(40, 5, 10),
(40, 5, 20),
(40, 5, 30),
(40, 10, 10),
(40, 10, 20),
(40, 10, 30),
(40, 20, 10),
(40, 20, 20),
(40, 20, 30)]]
Yes, using the range function , with step.是的,使用范围 function ,有步骤。
range(start, stop, step)范围(开始、停止、步进)
A simple way of doing this is like this:一个简单的方法是这样的:
array = []
for x in range(30, 45, 5):
y_tuple_multipler = 1
sub_array = []
for y in range(1, 4):
y_tuple = 5 * y_tuple_multipler
for z in range(10, 40, 10):
sub_array.append((x, y_tuple, z))
y_tuple_multipler *= 2
array.append(sub_array)
print(array)
You can probably get more pythonic
, but simplicity is always good (and easier to debug multiple loops)您可能可以获得更多pythonic
,但简单总是好的(并且更容易调试多个循环)
You can try this list comprehensions:你可以试试这个列表推导:
l1 =[30,35,40]
l2 =[5,10,20]
l3= [10,20,30]
l = [[(i1,i2,i3) for i2 in l2 for i3 in l3 ]for i1 in l1]
If you want to add number just add it to the inner tuple (for exmaple, 10):如果要添加数字,只需将其添加到内部元组(例如,10):
l = [[(10,i1,i2,i3) for i2 in l2 for i3 in l3 ]for i1 in l1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.