如何在 python 中创建顺序组合列表?
How to create a sequential combined list in python?
我有一个列表 ['a', 'b', 'c', 'd'] 我需要一个列表 ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'].
我一直在查看 itertools,但我不知道如何进行这项工作。
对于 all combinations,代码为:
from itertools import permutations
stuff = ['a','b','c','d']
for i in range(0, len(stuff)+1):
for subset in permutations(stuff, i):
print(subset)
对于 return 只有顺序组合,我需要做什么?我想我可以随时检查每个排列的顺序,但这似乎不是最好的方法。
你可以用一个不理解的列表来做到这一点:
>>> [''.join(['a', 'b', 'c', 'd'])[i:j+1] for i in range(4) for j in range(i, 4)]
['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
虽然不确定你是否想这样做。
很简单:
stuff = ['a','b','c','d']
print([''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)])
给予
['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
我认为这应该可以解决问题:
items = ['a', 'b', 'c', 'd']
combinations = []
for i, x in enumerate(items):
combinations.append(x)
accum = x
for y in items[i+1:]:
accum += y
combinations.append(accum)
这个函数做到了:
def subsequences(lst):
return [''.join(lst[i: j+1])
for i in range(len(lst))
for j in range(i, len(lst))]
>>> subsequences(['a', 'b', 'c'])
['a', 'ab', 'abc', 'b', 'bc', 'c']
>>> subsequences(['a', 'b', 'c', 'd'])
['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
另一种可能的解决方案(不使用 itertools
),这次为了清晰起见使用辅助程序:
def combine(lst):
return [''.join(lst[0:i+1]) for i in xrange(len(lst))]
lst = ['a', 'b', 'c', 'd']
sum([combine(lst[i:]) for i in xrange(len(lst))], [])
=> ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
我有一个列表 ['a', 'b', 'c', 'd'] 我需要一个列表 ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'].
我一直在查看 itertools,但我不知道如何进行这项工作。
对于 all combinations,代码为:
from itertools import permutations
stuff = ['a','b','c','d']
for i in range(0, len(stuff)+1):
for subset in permutations(stuff, i):
print(subset)
对于 return 只有顺序组合,我需要做什么?我想我可以随时检查每个排列的顺序,但这似乎不是最好的方法。
你可以用一个不理解的列表来做到这一点:
>>> [''.join(['a', 'b', 'c', 'd'])[i:j+1] for i in range(4) for j in range(i, 4)]
['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
虽然不确定你是否想这样做。
很简单:
stuff = ['a','b','c','d']
print([''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)])
给予
['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
我认为这应该可以解决问题:
items = ['a', 'b', 'c', 'd']
combinations = []
for i, x in enumerate(items):
combinations.append(x)
accum = x
for y in items[i+1:]:
accum += y
combinations.append(accum)
这个函数做到了:
def subsequences(lst):
return [''.join(lst[i: j+1])
for i in range(len(lst))
for j in range(i, len(lst))]
>>> subsequences(['a', 'b', 'c'])
['a', 'ab', 'abc', 'b', 'bc', 'c']
>>> subsequences(['a', 'b', 'c', 'd'])
['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
另一种可能的解决方案(不使用 itertools
),这次为了清晰起见使用辅助程序:
def combine(lst):
return [''.join(lst[0:i+1]) for i in xrange(len(lst))]
lst = ['a', 'b', 'c', 'd']
sum([combine(lst[i:]) for i in xrange(len(lst))], [])
=> ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']