【问题标题】:To find a list of possible sub array from a array从数组中查找可能的子数组列表
【发布时间】:2021-07-04 12:45:52
【问题描述】:

我正在努力寻找一种方法来从列表中获取所有可能的子列表 比如考虑一个列表[1,2,3,4] 我想要像

这样的子列表
sublists = [[1, 2, 3, 4]],[[1], [2, 3, 4]],[[1, 2], [3, 4]],[[1], [2], [3, 4]],[[1, 2, 3], [4]],[[1], [2, 3], [4]],[[1, 2], [3], [4]],[[1], [2], [3], [4]]

请告诉是否有任何方法可以做到这一点

【问题讨论】:

  • 到目前为止你有什么尝试?
  • @IoaTzimas 是的,我尝试过 lst = [1, 2, 3, 4, 5] lstt = [] for i in range(len(lst)): l1 = [] l2 = lst[i:] l3 = lst[:i] l1.append(l2) l1.append(l3) lstt.append(l1) print(lstt)

标签: python arraylist


【解决方案1】:

您可以使用itertools.combinations 选择子列表的开始和结束:

from itertools import combinations

lst = [1,2,3,4,5]

sublists = [ lst[i:j] for i,j in combinations(range(len(lst)+1),r=2) ]

产量:

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

【讨论】:

  • 兄弟我不希望这个结果,我期待包含主列表中每个值的子列表
  • 您认为这里缺少哪个子列表?
  • 我想要类似'对于像 [1,2,3,4] 这样的列表,我想要 [ [1, 2, 3, 4] ],[ [1], [2, 3, 4 ] ],[ [1, 2], [3, 4] ],[ [1], [2], [3, 4] ],[ [1, 2, 3], [4] ],[ [1 ], [2, 3], [4] ],[ [1, 2], [3], [4] ],[ [1], [2], [3], [4] ]'
【解决方案2】:

你也可以试试这个

def  sub_lists (l):
    lists = []
    for i in range(len(l) + 1):
        l2=[]
        for j in range(i):
            l2.append(l[j: i])
        lists.append(l2.copy())
        l2.clear()
    return lists
l1 = [1, 2, 3,4,5]
print(sub_lists(l1))

【讨论】:

  • :(@LoneWolf,我会试试的
  • 请尝试一次
【解决方案3】:

您可以将此视为stars and bars 问题。从集合{1, 2, 3, 4} 开始,我们可以选择在任意两个元素之间放置一个条形图,例如1 | 2 3 | 4,对应于子集[1], [2, 3], [4]。有n-1 可以放置条的位置,从而产生2^(n-1) 不同的位置。这是使用itertools.product 的一种方法:

from itertools import product

def subsets(xs):
  n = len(xs)
  inds = list(range(1,n))
  for bs in product([True, False], repeat=len(inds)):
    cutoffs = [0] + [i for i, b in zip(inds, bs) if b] + [n] 
    zs = zip(cutoffs, cutoffs[1:])
    yield [xs[i:j] for i, j in zs]

list(subsets([1,2,3,4]))
# [[[1], [2], [3], [4]],
#  [[1], [2], [3, 4]],
#  [[1], [2, 3], [4]],
#  [[1], [2, 3, 4]],
#  [[1, 2], [3], [4]],
#  [[1, 2], [3, 4]],
#  [[1, 2, 3], [4]],
#  [[1, 2, 3, 4]]]  

【讨论】:

    猜你喜欢
    • 2011-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多