【问题标题】:Python how can create a subset from a integer array list based on a range?Python如何根据范围从整数数组列表中创建子集?
【发布时间】:2021-03-10 18:53:24
【问题描述】:

我正在寻找一种方法来根据特定范围从整数数组中获取子集 例如

Input
array1=[3,5,4,12,34,54]

#Now getting subset for every 3 element

Output
subset= [(3,5,4), (12,34,54)]

我知道这可能很简单,但没有找到获得此输出的正确方法

感谢您的帮助

谢谢

【问题讨论】:

标签: python-3.x


【解决方案1】:

考虑使用 list comprehension

>>> array1 = [3, 5, 4, 12, 34, 54]
>>> subset = [tuple(array1[i:i+3]) for i in range(0, len(array1), 3)]
>>> subset
[(3, 5, 4), (12, 34, 54)]

其他相关文档的链接:

【讨论】:

    【解决方案2】:
    arr = [1,2,3,4,5,6]
    sets = [tuple(arr[i:i+3]) for i in range(0, len(arr), 3)]
    print(sets)
    

    我们从我们制作的数组中获取一系列值,形成一个元组。范围由 for 循环确定,该循环以三步为单位进行迭代,因此每 3 个项目后仅创建一个元组。

    【讨论】:

      【解决方案3】:

      你可以使用代码:

      from itertools import zip_longest
      input_list = [3,5,4,12,34,54]
      iterables = [iter(input_list)] * 3
      slices = zip_longest(*iterables, fillvalue=None)
      output_list =[]
      for slice in slices:
          my_list = [slice]
          # print(my_list)
          output_list = output_list + my_list
      print(output_list) 
      

      您可以使用 itertools 中的 zip_longest 函数 https://docs.python.org/3.0/library/itertools.html#itertools.zip_longest

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-26
        • 1970-01-01
        • 2013-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多