【问题标题】:How to simultaneously loop over different lists?如何同时遍历不同的列表?
【发布时间】:2014-03-11 22:08:43
【问题描述】:

我正在尝试遍历字符串列表:

someplace["Canada", "USA", "England"]

for charNum in range(len(lst)): #charNum the length of the characters
    print(lst[charNum])

for country in range(len([charNum])): #country is the the string
   print(lst[charNum][country])

我想要达到的输出是这样的:

c  U  E
a  S  n
n  A  g
a     l 
d     a 
a     n
      d

更多细节:

for k in range(len(lst[0])):
    print(lst[0][k])

如果运行它会打印出来

   c
   a
   n
   a
   d
   a

这是因为它的索引长度为 0。但我必须遍历其他数字:0、1、2。

我取得了一些进展,我创建了一个嵌套的 for 循环:

for i in range(len(lst)):  # length of list
    for j in range(len(lst[i])): # length of each string
        print(lst[i][j])

【问题讨论】:

    标签: python string list loops


    【解决方案1】:

    使用itertools.izip_longest 同时循环所有

    from itertools import izip_longest  # zip_longest in python 3
    places = ["Canada", "USA", "England"]
    for chars in izip_longest(*places, fillvalue=' '):
        print(' '.join(chars))
    

    输出:

    C U E
    a S n
    n A g
    a   l
    d   a
    a   n
        d
    

    过程:

    izip_longest 的输出为:

    [('C', 'U', 'E'), ('a', 'S', 'n'), ('n', 'A', 'g'), ('a', ' ', 'l'), ('d', ' ', 'a'), ('a', ' ', 'n'), (' ', ' ', 'd')]
    

    然后for 循环将每个“行”依次分配给chars,从('C', 'U', 'E') 开始

    ' '.join(chars) 将该元组组合成一个字符串,每个列表成员之间有空格。对于第一个元素,那就是 'C U E'

    【讨论】:

    • 我还没学会用这个方法。我学习了python 3的开始步骤。我坚持如何在for循环中更改索引号。
    • @user3339203,我已经用更完整的过程解释编辑了答案
    • 这样,我们不会改变索引号。我们正在直接访问成员
    【解决方案2】:

    要内置列表,您需要有一个。

    my_list = ["Paris"]
    

    【讨论】:

      【解决方案3】:
        SomePlaces = ['Canada', 'USA',  'England'] //Array
        for SomePlaces in range(len(lst)):
         print 'Places :', lst[SomePlaces]
      

      注意:我没有测试它,如果我错了,请见谅。

      【讨论】:

      • 如果你不测试你的代码,不要抱怨被否决。您混合了变量名 SomePlaceslst,您的评论语法错误,但最重要的是,您的答案甚至没有尝试打印 OP 要求的内容!
      猜你喜欢
      • 2011-08-03
      • 2012-05-26
      • 2021-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多