说我有一个列表,['a', 'b', 'c', 'd']
。 Python中是否有任何内置函数或方法可以从第一个项目开始轻松创建所有连续子列表(即子序列)?:
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
在Python中?
请注意,我排除了['a' ,'c']
,['a', 'd']
,['b']
,['c']
或['d']
答案 0 :(得分:5)
要匹配您的示例输出(前缀),您只需使用:
prefixes = [your_list[:end] for end in xrange(1, len(your_list) + 1)]
答案 1 :(得分:4)
您可以使用简单的list comprehension:
执行此操作>>> l = ['a', 'b', 'c', 'd']
>>>
>>> [l[:i+1] for i in range(len(l))]
[['a'], ['a', 'b'], ['a', 'b', 'c'], ['a', 'b', 'c', 'd']]
另请参阅:range()
如果您使用的是Python 2.x,请改用xrange()
。
答案 2 :(得分:1)
比使用(x)range
更多Pythonic(与Python 2或Python 3的解决方案相同):
lst = list('abcde')
prefixes = [ lst[:i+1] for i,_ in enumerate(lst) ]
如果您确定空列表应该是有效(零长度)前缀,那么小的黑客将包含它:
# Include 0 as an slice index and still get the full list as a prefix
prefixes = [ lst[:i] for i,_ in enumerate(lst + [None]) ]
答案 3 :(得分:1)
作为替代方案:
def prefixes(seq):
result = []
for item in seq:
result.append(item)
yield result[:]
for x in prefixes(['a', 'b', 'c', 'd']):
print(x)