I want to create a sequence of tuples of varying lengths. For example sometimes I might want a sequence with 3 tuples:
((0.0, 100.0), (0.0, 100.0), (0.0,100.0))
other times I might want a sequence with 4 tuples:
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0), (0.0, 100.0))
I'm using Python 2.7. What is the quickest way to do this?
Just use an ordinary generator with range
:
>>> tuple((0., 100.) for _ in range(3))
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0))
>>> tuple((0., 100.) for _ in range(4))
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0), (0.0, 100.0))
You could also use multiplication, but this can have unintended effects if you decide to include mutable objects, as they are duplicated by reference:
>>> ((0., 100.),) * 3
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0))
>>> ((0., 100.),) * 4
((0.0, 100.0), (0.0, 100.0), (0.0, 100.0), (0.0, 100.0))
>>> a = ((0., 100., []),) * 3
>>> a
((0.0, 100.0, []), (0.0, 100.0, []), (0.0, 100.0, []))
>>> a[0][-1].append(1)
>>> a
((0.0, 100.0, [1]), (0.0, 100.0, [1]), (0.0, 100.0, [1]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.