For循环For循环Python

2024-10-01 00:34:03 发布

您现在位置:Python中文网/ 问答频道 /正文

l1 = ["a", "b", "c"]
l2 = ["a", "b", "c"]

for i in l1:
    print(i)
    for i in l2:
        print(i)

输出:aabcbabccabc如何获得这样的输出?:aabbcc


Tags: inl1forprintl2aabbccaabcbabccabc
3条回答

您可以使用zip内置函数。它将返回您传递的所有iterables的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="")

使用zip

l1 = ["a", "b", "c"]
l2 = ["a", "b", "c"]


for a, b in zip(l1, l2):
  print(a)
  print(b)

如果阵列大小相同,可以执行以下操作:

for i in range((len(l1)):
    print(l1[i])
    print(l2[i])

相关问题 更多 >