我将如何进行以下操作?
class a:
def get(self):
return (1, 2)
i = a() #this is variable that i wont have access directly and should be accessed only from list P below
P = [i, i, i, i]
Q = [P, P, P, P]
我想要的是
L = [list of all i.get() results iterating through Q and P]
例如
L = [px.get() for px in P for P in Q] # I want something like this
即
L = [(1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2)]
答案 0 :(得分:2)
使用列表理解:
L = [i.get() for P in Q for i in P]
这会为您提供[Q[0][0].get(), Q[0][1].get(), ..., Q[-1][-2].get(), Q[-1][-1].get()]
双循环就像是列表推导之外的嵌套for循环,上面相当于:
L = []
for P in Q:
for i in P:
L.append(i.get())
列表推导遵循相同的循环顺序,嵌套转换为从左到右列出的循环。
答案 1 :(得分:0)
可以使用Python中的*
运算符(即multiplying a list)复制列表:
>>> [i.get()] * (len(P) + len(Q))
[(1,2), (1,2), (1,2), (1,2), (1,2), (1,2), (1,2), (1,2)]