我的代码。
import random
randomlist = []
result_list=[]
l=int(input('Enter List Length'))
for i in range(0,l):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)
n=int(input('composite range:'))
composite_list = [randomlist[x:x + n] for x in range(0, len(randomlist), n)]
print(composite_list)
# zip inner list
for i in composite_list:
#stucked here
我希望将所有的列表元素压缩到一个新的列表中,例如: 随机列表。[25, 6, 15, 7, 21, 30, 10, 14, 3]
composite_list:[[25, 6, 15], [7, 21, 30], [10, 14, 3]]
压缩后输出列表。[[25, 7, 10],[6, 21, 14],[15, 30, 3]]
因为列表中元素的数量 composite_list
是随机的。我不知道如何使用 zip()
你可以做如下操作。
rand_lst = [25, 6, 15, 7, 21, 30, 10, 14, 3]
it = iter(rand_lst)
comp_lst = list(zip(it, it, it))
# [(25, 6, 15), (7, 21, 30), (10, 14, 3)]
trans_lst = list(zip(*comp_lst))
# [(25, 7, 10), (6, 21, 14), (15, 30, 3)]
这使用的是旧的"zip
iterator with itself "模式来创建分块。然后你可以通过使用 *
操作员。这也是一步到位的。
it = iter(rand_lst)
trans_lst = list(zip(*zip(it, it, it)))
使用:
list(zip(*composite_list))
# output is a list of tuples
Or:
list(map(list, zip(*composite_list)))
# output is a list of lists
来精确地查看你想要的输出。
使用 numpy
:
import numpy as np
np.array(composite_list).T.tolist()
:输出。
[[25, 7, 10], [6, 21, 14], [15, 30, 3]]
告诫: 可能会更好,如果你将保持你的整个流程中的 numpy
,否则转换为 numpy
可能有点开销。