【问题标题】:For loop in for loop - Python [duplicate]for循环中的for循环-Python [重复]
【发布时间】: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

【问题讨论】:

    标签: python loops for-loop


    【解决方案1】:

    我们可以使用下面的zip函数

    print(*(y for x in zip(l1,l2) for y in x))
    

    【讨论】:

      【解决方案2】:

      如果数组大小相同,您可以这样做:

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

      【讨论】:

        【解决方案3】:

        使用zip:

        l1 = ["a", "b", "c"]
        l2 = ["a", "b", "c"]
        
        
        for a, b in zip(l1, l2):
          print(a)
          print(b)
        

        【讨论】:

        • 谢谢罗尼。这就是我需要的
        【解决方案4】:

        您可以使用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="")
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-04
          • 1970-01-01
          • 2010-11-14
          • 1970-01-01
          • 1970-01-01
          • 2019-01-08
          • 2014-03-23
          相关资源
          最近更新 更多