Reputation: 75
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:
[[(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)]]
Upvotes: 2
Views: 86
Reputation: 5745
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):
l = [[(10,i1,i2,i3) for i2 in l2 for i3 in l3 ]for i1 in l1]
Upvotes: 1
Reputation: 21312
Yes, using the range function, with step.
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)
Upvotes: 1