Skip to main content
 首页 » 编程设计

python之通过合并多个 (4) 其他列表创建一个新列表

2024年09月07日11dyllove98

我试图从其他列表 a,b,c,d 中创建一个列表 new_list 并搜索了一段时间,这就是我想出的

a = [1]  
b = ['b1','b2','b3',...]  
c = ['c1','c2','c3',...]  
d = ['d1','d2','d3',...]  
count = 0  
output = []  
 
for item in [b,c,d]:      
     output.append(item[0]) 
     count += 1 
 
new_list = list(a + output)  
print (a1)' 
>>> [1, 'b1', 'c1', 'd1'] 

它打印出我想要的内容,但我的问题是我无法继续... 我需要让它打印下一个和下一个 new_list 直到列表 b,c,d 用完所有元素。

# desired output: 
[1, 'b1', 'c1', 'd1'] 
[1, 'b2', 'c2', 'd2'] 
[1, 'b3', 'c3', 'd3'] 
[..... and so on....] 

我已经尝试过嵌套循环,count in item[0] 并提取每个元素,但这是我最接近的,真的需要一些帮助或指导。

请您参考如下方法:

对第一个列表使用 itertools.repeat()(实际上是迭代),然后使用 zip() 所有可迭代对象。

>>> zip(itertools.repeat(1), b, c, d) 
[(1, 'b1', 'c1', 'd1'), (1, 'b2', 'c2', 'd2'), (1, 'b3', 'c3', 'd3')]