【问题标题】:Display grouped list of items from python list cyclically循环显示python列表中的项目分组列表
【发布时间】:2020-08-01 01:50:04
【问题描述】:

我有一个数组,给定组中的项目数和组数,我需要在循环中循环打印数组。 数组-[1,2,3,4,5,6] 组- 4 迭代 - 7

输出应该是:

['1', '2', '3', '4']
['5', '6', '1', '2']
['3', '4', '5', '6']
['1', '2', '3', '4']
['5', '6', '1', '2']
['3', '4', '5', '6']
['1', '2', '3', '4']

【问题讨论】:

    标签: python arrays list


    【解决方案1】:

    np.resize在这里很方便:

    np.resize([1,2,3,4,5,6],(7,4))
    # array([[1, 2, 3, 4],
    #        [5, 6, 1, 2],
    #        [3, 4, 5, 6],
    #        [1, 2, 3, 4],
    #        [5, 6, 1, 2],
    #        [3, 4, 5, 6],
    #        [1, 2, 3, 4]])
    

    【讨论】:

    • @PaulPanzer 我喜欢这个解决方案,使用更多命令我可以实现我想要的输出,但与公认的解决方案相比,这有点慢。感谢您的回答
    【解决方案2】:

    这是一种方法。我两次创建了一个由输入数组组成的更长的列表,所以是这样的:

    [1,2,3,4,5,6,1,2,3,4,5,6]
    

    然后将其从起始索引i 分割到i+NN 是组的大小,在本例中为 4)。

    a = [1,2,3,4,5,6]
    
    N = 4 # Number of elements in a group
    
    aa = a+a # create a list composed of the array 'a' twice
    
    i = 0 # starting index
    
    for loop in range(7):
        # extract the elements from the doublelist
        print(aa[i:i+N])
    
        # The next starting point has to be within the range of array 'a'
        i = (i+N)%len(a)
    

    输出:

    [1, 2, 3, 4]
    [5, 6, 1, 2]
    [3, 4, 5, 6]
    [1, 2, 3, 4]
    [5, 6, 1, 2]
    [3, 4, 5, 6]
    [1, 2, 3, 4]
    

    【讨论】:

      【解决方案3】:

      一种解决方案是将itertools.cycleitertools.slice 结合使用。

      from itertools import cycle, islice
      
      def format_print(iterable, group_size, iterations):
          iterable = cycle(iterable)
          for _ in range(iterations):
              print(list(islice(iterable, 0, group_size)))
      
      format_print(range(1, 7), 4, 7)
      

      输出:

      [1, 2, 3, 4]
      [5, 6, 1, 2]
      [3, 4, 5, 6]
      [1, 2, 3, 4]
      [5, 6, 1, 2]
      [3, 4, 5, 6]
      [1, 2, 3, 4]
      

      如果需要打印字符串列表,cycle(iterable)可以换成cycle(map(str, iterable))

      【讨论】:

      • GZ0,有没有办法在打印时将列表项从 int 转换为 str
      • @SatyaV 是的。只需将cycle(iterable) 更改为cycle(map(str, iterable))
      【解决方案4】:

      您可以尝试以下使用itertools.cycle

      import itertools
      
      t = [1, 2, 3, 4, 5, 6]
      
      number_of_elms_in_a_group = 4
      iteration_number = 7
      
      groups = []
      group = []
      for i, x in enumerate(itertools.cycle(t)):
          if len(groups) >= iteration_number:
              break
          if i % number_of_elms_in_a_group == 0 and i != 0:
              groups.append(group)
              group = []
          group.append(x)
      
      # At this point,
      # groups == [[1, 2, 3, 4], [5, 6, 1, 2], [3, 4, 5, 6],
      #            [1, 2, 3, 4], [5, 6, 1, 2], [3, 4, 5, 6],
      #            [1, 2, 3, 4]]
      for group in groups:
          print(group)
      

      打印出来的

      [1, 2, 3, 4]
      [5, 6, 1, 2]
      [3, 4, 5, 6]
      [1, 2, 3, 4]
      [5, 6, 1, 2]
      [3, 4, 5, 6]
      [1, 2, 3, 4]
      

      【讨论】:

        【解决方案5】:

        如果速度是个问题numpy 可以很好地做到这一点;但它会以记忆为代价

        import numpy as np
        
        arr = [1,2,4,5,6]
        iteration = 7
        group = 4
        

        np.array([arr]*(group+2)).flatten().reshape(-1, group)[:it]

        [[1, 2, 3, 4],
        [5, 6, 1, 2],
        [3, 4, 5, 6],
        [1, 2, 3, 4],
        [5, 6, 1, 2],
        [3, 4, 5, 6],
        [1, 2, 3, 4]])
        

        【讨论】:

          【解决方案6】:

          另一种方法(虽然很明显)。使用tile 将数组重复足够多次,然后对其进行整形:

          np.tile(array,Group*Iterations//array.size+1)[:Group*Iterations].reshape(Iterations,Group))
          

          如果array是一个列表,首先将其转换为numpy数组:

          import numpy as np
          array = np.array(array)
          

          输出:

          [[1 2 3 4]
           [5 6 1 2]
           [3 4 5 6]
           [1 2 3 4]
           [5 6 1 2]
           [3 4 5 6]
           [1 2 3 4]]
          

          【讨论】:

            【解决方案7】:

            这是另一种不使用任何库的方式:

            array = [1, 2, 3, 4, 5, 6]
            
            number_of_elements = 4
            iterations = 7
            
            iterations_groups = []
            elements_group = []
            
            for y in range(iterations):
                for i, x in enumerate(array):
                    if len(iterations_groups) == iterations:
                        break
                    if len(elements_group) < number_of_elements:
                        elements_group.append(x)
                    else:
                        iterations_groups.append(elements_group)
                        elements_group = []
                        elements_group.append(x)
            
            for group in iterations_groups:
                print(group)
            

            输出:

            [1, 2, 3, 4]
            [5, 6, 1, 2]
            [3, 4, 5, 6]
            [1, 2, 3, 4]
            [5, 6, 1, 2]
            [3, 4, 5, 6]
            [1, 2, 3, 4]
            

            【讨论】:

              【解决方案8】:

              我得到了这个解决方案。感谢大家发布答案,您的答案帮助我提高了知识。

              from itertools import cycle
              
              def sub_list(list_in, list_size, num_iter):
                cycle_list = cycle(list_in)
                for i in range(num_iter):
                  print([str(next(cycle_list)) for i in range(list_size)])
              
              sub_list([1,2,3,4,5,6], 4, 7)
               
              

              输出是:

              ['1', '2', '3', '4']
              ['5', '6', '1', '2']
              ['3', '4', '5', '6']
              ['1', '2', '3', '4']
              ['5', '6', '1', '2']
              ['3', '4', '5', '6']
              ['1', '2', '3', '4']
              

              【讨论】:

              • @Gorisanson,谢谢你给我'itertools.cycle'的提示。我对此进行了一些探索并得到了这个解决方案:)
              • 您可以从 cycle_list = cycle(map(str,list_in)) 开始您的函数,这样您就不必在循环中将每个项目转换为字符串。
              【解决方案9】:

              我可以看到很多解决方案,但我在不使用任何库的情况下为您提供解决方案。可能你会喜欢它。我使用字典创建了一个循环linked_list,然后解决了这个问题。

              output = []
              
              
              def execute(grp, iteration, linked_list):
                  key = 0
                  for a in range(iteration):
                      l = []
                      for b in range(grp):
                          value = linked_list[key]["value"]
                          key = linked_list[key]["key"]
                          l.append(value)
              
                      output.append(l)
                  return output
              
              
              def get_linked_list(Array):
                  linked_list = {}
                  for count, a in enumerate(Array):
                      if count == len(Array) - 1:
                          linked_list[count] = {"key": 0, "value": a}
                      else:
                          linked_list[count] = {"key": count + 1, "value": a}
                  return linked_list
              
              
              Array = [11, 22, 33, 44, 55,66]
              Group = 4
              Iterations = 7
              print(execute(Group, Iterations, get_linked_list(Array)))
              

              【讨论】:

                【解决方案10】:

                你可以只用切片来做到这一点。

                a = [1,2,3,4,5,6]
                
                for _ in range(7):
                    print(a[0:4])
                    a = a[4:] + a[0:4]
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多