Let's say that list 'l' contains tuples and has an even number of elements. Every tuple consists of 3 numbers (int) 0 <= x <= 255
And now the fun part, there is a following pattern:
l[0] = l[1], l[2] = l[3], l[4] = l[5] .....
So the list looks for example like this:
l[0] = (100, 200, 10)
l[1] = (100, 200, 10)
l[2] = (250, 45, 30)
l[3] = (250, 45, 30)
l[4] = (30, 10, 5)
l[5] = (30, 10, 5)
.......
The problem is not how to generate the list because that's easy, I want to know if there is any way to do it in one line, using some smart tricks and list comprehension etc.
Right now the code looks like this:
from random import randint
b = []
for _ in range(4):
b += [(randint(0, 255), randint(0, 255), randint(0, 255))]*2
# example for how b looks:
# [(206, 89, 40), (206, 89, 40), (36, 115, 91), (36, 115, 91), (232, 55, 96), (232, 55, 96), (183, 114, 179), (183, 114, 179)]
答案 0 :(得分:2)
您可以在列表理解中使用双循环:
b = [value for _ in range(4)
for value in [(randint(0, 255), randint(0, 255), randint(0, 255))] * 2]