【问题标题】:While loop within for loop for list of lists用于列表列表的 for 循环内的 while 循环
【发布时间】:2017-11-27 02:15:20
【问题描述】:

我正在尝试创建一个包含字符串列表的大列表。我遍历输入的字符串列表并创建一个临时列表。 输入:

['Mike','Angela','Bill','\n','Robert','Pam','\n',...]

我想要的输出:

[['Mike','Angela','Bill'],['Robert','Pam']...]

我得到了什么:

[['Mike','Angela','Bill'],['Angela','Bill'],['Bill']...]

代码:

for i in range(0,len(temp)):
        temporary = []
        while(temp[i] != '\n' and i<len(temp)-1):
            temporary.append(temp[i])
            i+=1
        bigList.append(temporary)

【问题讨论】:

标签: python list for-loop


【解决方案1】:

使用itertools.groupby

from itertools import groupby
names = ['Mike','Angela','Bill','\n','Robert','Pam']
[list(g) for k,g in groupby(names, lambda x:x=='\n') if not k]
#[['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]

【讨论】:

    【解决方案2】:

    修复您的代码,我建议直接迭代每个元素,附加到嵌套列表 -

    r = [[]]
    for i in temp:
        if i.strip():
            r[-1].append(i)
        else:
            r.append([])
    

    请注意,如果 temp 以换行符结尾,r 将有一个尾随的空 [] 列表。不过你可以摆脱它:

    if not r[-1]:
        del r[-1]
    

    另一个选项是使用itertools.groupby,其他回答者已经提到过。虽然,您的方法更高效。

    【讨论】:

      【解决方案3】:

      您的 for 循环很好地扫描了 temp 数组,但内部的 while 循环正在推进该索引。然后你的while循环会减少索引。这导致了重复。

      temp = ['mike','angela','bill','\n','robert','pam','\n','liz','anya','\n'] 
      # !make sure to include this '\n' at the end of temp!
      bigList = [] 
      
      temporary = []
      for i in range(0,len(temp)):
              if(temp[i] != '\n'):
                  temporary.append(temp[i])
                  print(temporary)
              else:
                  print(temporary)
                  bigList.append(temporary)
                  temporary = []
      

      【讨论】:

        【解决方案4】:

        你可以试试:

        a_list = ['Mike','Angela','Bill','\n','Robert','Pam','\n']
        
        result = []
        
        start = 0
        end = 0
        
        for indx, name in enumerate(a_list):    
            if name == '\n':
                end = indx
                sublist = a_list[start:end]
                if sublist:
                    result.append(sublist)
                start = indx + 1    
        
        >>> result
        [['Mike', 'Angela', 'Bill'], ['Robert', 'Pam']]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-07-21
          • 2019-05-14
          • 2018-11-05
          • 2016-04-06
          • 2013-03-09
          • 2019-11-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多