【问题标题】:Loop character A/B alternately交替循环字符 A/B
【发布时间】:2016-08-29 11:24:27
【问题描述】:

如何在 python 循环中交替打印 A/B 字符?

我期望的结果:

oneA
twoB
threeA
fourB
...

【问题讨论】:

  • 直到哪个值?如果只是一对,您可以输入“一”、“二”等。否则我们必须想出一个更好的计划。

标签: python loops for-loop


【解决方案1】:

您可以使用itertools.cycle 重复序列。这通常与zip 一起使用以遍历较长的列表,同时重复较短的列表。例如

import itertools
for i,j in zip(['one', 'two', 'three', 'four'], itertools.cycle('AB')):
    print(i+j)

输出

oneA
twoB
threeA
fourB

【讨论】:

【解决方案2】:

试试这个:

l1 = ['A','B']
l2 = ['one','two','three','four']
for i,val in enumerate(l2):
    print(val + l1[i%len(l1)])

【讨论】:

    【解决方案3】:

    您也可以尝试在递增的 for 循环的索引上使用模运算符 % 来让数字交替字母:

    list_num = ['one', 'two', 'three', 'four', 'five', 'six']
    list_alpha = ['A', 'B']
    list_combined = []
    for i in range(0, len(list_num)):
        list_combined.append(list_num[i] + (list_alpha[1] if i % 2 else list_alpha[0]))
    list_combined
    >>> ['oneA', 'twoB', 'threeA', 'fourB', 'fiveA', 'sixB']
    

    【讨论】:

      【解决方案4】:

      类似:

      alternate_words = ['A', 'B']
          count = 0
      
      while count < 5:
          print count+1, alternate_words[count % len(alternate_words)]
          count += 1
      

      输出:

      1 个

      2 乙

      3A

      4 乙

      5 个

      【讨论】:

        【解决方案5】:

        我认为这会有所帮助 ->

        a1 = ['A','B']
        a2 = ['one','two','three','four']
        for i in range(len(a2)):
            print a2[i]+a1[i%2]
        

        【讨论】:

          【解决方案6】:

          根据@Graipher 的建议,不要将zip()itertools.cycle() 结合使用,更好、更简单的解决方案将是使用itertools.product(),即

          输入迭代的笛卡尔积。

          大致相当于生成器表达式中的嵌套 for 循环。例如,product(A, B) 返回的结果与 ((x,y) for x in A for y in B) 相同。

          https://docs.python.org/2/library/itertools.html#itertools.product

          words = ['one', 'two', 'three'] 
          for word, i in itertools.product(words, ('A', 'B')):
              print(word+i)
          

          【讨论】:

            猜你喜欢
            • 2023-03-04
            • 1970-01-01
            • 2018-10-03
            • 1970-01-01
            • 2011-06-21
            • 2020-12-28
            • 1970-01-01
            • 2023-04-05
            • 1970-01-01
            相关资源
            最近更新 更多