【发布时间】:2020-10-18 16:04:27
【问题描述】:
l1 = ["a", "b", "c"]
l2 = ["a", "b", "c"]
for i in l1:
print(i)
for i in l2:
print(i)
输出:aabcbabccabc
我怎样才能得到这样的输出?:
aabbcc
【问题讨论】:
l1 = ["a", "b", "c"]
l2 = ["a", "b", "c"]
for i in l1:
print(i)
for i in l2:
print(i)
输出:aabcbabccabc
我怎样才能得到这样的输出?:
aabbcc
【问题讨论】:
我们可以使用下面的zip函数
print(*(y for x in zip(l1,l2) for y in x))
【讨论】:
如果数组大小相同,您可以这样做:
for i in range((len(l1)):
print(l1[i])
print(l2[i])
【讨论】:
使用zip:
l1 = ["a", "b", "c"]
l2 = ["a", "b", "c"]
for a, b in zip(l1, l2):
print(a)
print(b)
【讨论】:
您可以使用zip 内置函数。它将返回您传递的所有可迭代对象的 i-th item。见zip doc
在你的情况下:
for it in zip(l1, l2):
# the * is for extracting the items from it
# sep="" does not print any spaces between
# end="" does avoid printing a new line at the end
print(*it, sep="", end="")
【讨论】: