我有以下三个字符串列表:
st1=["a","b"]
st2=["likes"]
st3=["programming","math"]
我希望输出如下:
a likes programming
b likes math
答案 0 :(得分:2)
使用itertools.cycle
from itertools import cycle
st1=["a","b"]
st2=["likes"]
st3=["programming","math"]
for i,j,k in zip(st1, cycle(st2), st3):
print(i+" "+j+" "+k)
输出:
a likes programming
b likes math
答案 1 :(得分:1)
如果st1
和st3
的长度相同,请尝试以下操作:
print(*[st1[i]+" "+st2[0]+" "+st3[i] for i in range(len(st1))], sep = '\n')
输出:
a likes programming
b likes math
答案 2 :(得分:1)
将zip_longest
与for
循环一起使用:
for x,y,z in zip_longest(st1,st2*2,st3):
print(x,y,z)
或者:
print('\n'.join([' '.join(i) for i in zip_longest(st1,st2*2,st3)]))
演示:
from itertools import zip_longest
st1=["a","b"]
st2=["likes"]
st3=["programming","math"]
for x,y,z in zip_longest(st1,st2*2,st3):
print(x,y,z)
其他演示:
from itertools import zip_longest
st1=["a","b"]
st2=["likes"]
st3=["programming","math"]
print('\n'.join([' '.join(i) for i in zip_longest(st1,st2*2,st3)]))
答案 3 :(得分:0)
完全动态的解决方案,您可以根据需要提供任意数量的大小不同的数组:
def generate_output(*args):
max_length = max([len(arg) for arg in args])
for i in range(max_length):
tmp = ""
for arg in args:
if len(arg) < max_length:
arg = arg + [arg[-1]] * (max_length - len(arg))
tmp += arg[i] + " "
print tmp
st1 = ['a','b']
st2 = ['likes']
st3 = ['programming','math','Bio']
st4 = ['and','or']
st5 = ['he']
st6 = ['loves']
st7 = ['piano','games', 'sport', 'reading']
generate_output(st1,st2,st3)
print('***')
generate_output(st1,st2,st3,st4,st5,st6,st7)
输出:
a likes programming
b likes math
b likes Bio
***
a likes programming and he loves piano
b likes math or he loves games
b likes Bio or he loves sport
b likes Bio or he loves reading
如OP示例中所示,当计算超出数组的总长度以将其与其他较长的数组连接时,将使用数组的最后一个元素。