按元素数量拆分子列表中的列表

split list in sub lists by number of elements

在python中,如果我有元素列表

l = ['a', 'b', 'c', 'd', 'e', 'f']

和一个数字列表

n = [2, 1, 3]

如何根据 n 中的数字拆分列表 l

并获取列表列表

[['a', 'b'], ['c'], ['d', 'e', 'f']]

有点糊涂,但还是:

ll = [[l.pop(0) for _ in range(k)] for k in n]

请注意,由于 pop() 的问题,此遍历不会完整保留列表。

你可以使用 islice:

>>> from itertools import islice
>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> n = [2, 1, 3]
>>> it = iter(l)
>>> out = [list(islice(it, size)) for size in n]
>>> out
[['a', 'b'], ['c'], ['d', 'e', 'f']]

我认为这将是最优化的,因为它只需要 len(n) 次迭代。

l = ['a', 'b', 'c', 'd', 'e', 'f']
n = [2, 1, 3]

res = []
temp = 0
for i in n:
    res.append(l[temp:temp+i])
    temp = temp+i
print res

Returns:

[['a', 'b'], ['c'], ['d', 'e', 'f']]

另一种方式

if __name__ == '__main__':
  l = ['a', 'b', 'c', 'd', 'e', 'f']
  n = [2, 1, 3]

  result = []
  for i in n:
    j = l[:i]
    result.append(j)
    l = l[i:]

  print result

给予

[['a', 'b'], ['c'], ['d', 'e', 'f']]

它不像其他一些解决方案那么短,但它确实非常可读

您可以从列表中创建一个迭代器。然后调用 next 适当的次数。

>>> l = ['a', 'b', 'c', 'd', 'e', 'f']
>>> n = [2, 1, 3]
>>> it = iter(l)
>>> [[next(it) for i in xrange(k)] for k in n]
[['a', 'b'], ['c'], ['d', 'e', 'f']]
cuts = [sum(n[:i]) for i in range(len(n) + 1)]
>>> [l[cuts[i]:cuts[i + 1]] for i in range(len(cuts) - 1)]
[['a', 'b'], ['c'], ['d', 'e', 'f']]

这使列表保持原样:

>>> l
['a', 'b', 'c', 'd', 'e', 'f']

您可以使用 numpy.split :

>>> np.split(l,[sum(n[:i]) for i in range(len(n))])
[array([], dtype=float64), array(['a', 'b'], 
      dtype='|S1'), array(['c'], 
      dtype='|S1'), array(['d', 'e', 'f'], 
      dtype='|S1')]