我正在尝试编写一个函数,以获取一个不同长度的列表作为输入,并返回压缩后的结果。 我所寻找的是将我下面的代码扩展到任意数量的列表。(我不能使用Zip Longest函数,因为我试图在我们的系统上这样做,因为我们的系统没有大多数python函数,包括 zip(最长函数)
这是我的密码:
a = [[1,2,3,4],[5,6],[7,8,9]]
def myzip(a):
temp1=[]
temp2=[]
temp3=[]
lens=[]
t=1
for i in a:
if(t==1):
temp1=i
lens.append(len(temp1))
t+=1
elif(t==2):
temp2=i
lens.append(len(temp2))
t+=1
elif(t==3):
temp3=i
lens.append(len(temp3))
for i in range(max(lens)):
if(i<len(temp1)):
print(temp1[i])
if(i<len(temp2)):
print(temp2[i])
if(i<len(temp3)):
print(temp3[i])
myzip(a)
输出:
1
5
7
2
6
8
3
9
4
此函数仅适用于3个列表,因为我使用临时列表来实现压缩结果,但我想使此代码适用于任意数量的列表。例如,我能够运行[[1,2,3,4],[5,6],[7,8,9],[11,33]]
或[[1,2,3,4],[5,6]]
或[[1,2,3,4],[5,6],[7,8,9],...,[25,22]]
类似的东西也可能对你有用:
输出
这个怎么样:
输出:
或者只是将其作为列表:
注意:@MarkM做了一个值得注意的评论-如果您的源数据包含
None
,此方法将有一个问题,因为它将过滤掉它们。您应该告诉zip_longest
使用不同的fillvalue
,在这种情况下,它不会显示在您的数据中。例如:如果由于非常具体的原因(如注释中所述)无法导入
itertools
,则可以使用文档(https://docs.python.org/3/library/itertools.html#itertools.zip_longest)中所示的实现:相关问题 更多 >
编程相关推荐