获取lis中相邻元素的所有组合

2024-06-11 19:04:20 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有可能得到所有元素的组合,以防它们是相邻的?
示例如下:

编辑:我想把它用在字符串上,而不仅仅是数字。例如:[Explain,it,to,me,please]

列表:

[0,1,2,3,4]

结果:

^{pr2}$

例如,在结果中不会有[0,2,3]等,因为0和{}不是上面排序列表中的邻居。在

我试图使用itertools.combinations,但它给出了所有的组合。在


Tags: to字符串元素编辑示例列表排序it
3条回答

与cpburnz-answer非常相似,它使用嵌套列表理解来实现。
不同的是,生成的列表按长度顺序排序,从大到小。在

[L[j:i+j] for i in xrange(len(L), 0, -1) for j in xrange(len(L) - i + 1)]

但是,如果您只需要生成列表,那么可以考虑使用生成器编写更具可读性的代码:

^{pr2}$

与上面的代码相同,但设计为迭代:

for sublist in all_windows(L):
    # does something with sublist

这里有一种使用itertools中的window配方的方法

from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result    
    for elem in it:
        result = result[1:] + (elem,)
        yield result

def all_windows(seq):
    for l in xrange(1, len(seq) + 1):
        for w in window(seq, l):
            yield w

您可以:

>>> L = [0,1,2,3,4]
>>> result = [L[i:j] for i in xrange(len(L)) for j in xrange(i + 1, len(L) + 1)]
>>> pprint.pprint(result)
[[0],
 [0, 1],
 [0, 1, 2],
 [0, 1, 2, 3],
 [0, 1, 2, 3, 4],
 [1],
 [1, 2],
 [1, 2, 3],
 [1, 2, 3, 4],
 [2],
 [2, 3],
 [2, 3, 4],
 [3],
 [3, 4],
 [4]]

然后,要按降序长度和升序值排序:

^{pr2}$

对于弦,它会产生:

>>> L = ['Explain', 'it', 'to', 'me', 'please']
>>> result = [L[i:j] for i in xrange(len(L)) for j in xrange(i + 1, len(L) + 1)]
>>> result.sort(key=lambda x: (-len(x), x))
>>> pprint.pprint(result)
[['Explain', 'it', 'to', 'me', 'please'],
 ['Explain', 'it', 'to', 'me'],
 ['it', 'to', 'me', 'please'],
 ['Explain', 'it', 'to'],
 ['it', 'to', 'me'],
 ['to', 'me', 'please'],
 ['Explain', 'it'],
 ['it', 'to'],
 ['me', 'please'],
 ['to', 'me'],
 ['Explain'],
 ['it'],
 ['me'],
 ['please'],
 ['to']]

相关问题 更多 >