【问题标题】:Python list comprehension to return edge values of a listPython列表推导返回列表的边缘值
【发布时间】:2010-04-15 06:38:59
【问题描述】:

如果我在 python 中有一个列表,例如:

stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]

长度为 n(在本例中为 9),我有兴趣创建长度为 n/2 的列表(在本例中为 4)。我想要原始列表中所有可能的 n/2 值集,例如:

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

是否有一些列表理解代码可以用来遍历列表并检索所有这些子列表?我不关心列表中值的顺序,我只是想找到一种生成列表的聪明方法。

【问题讨论】:

  • 我想我不清楚。我只对由原始列表中的连续值组成的子列表感兴趣,包括环绕。

标签: python data-structures iteration list-comprehension


【解决方案1】:
>>> stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> n=len(stuff)
>>>
>>> [(stuff+stuff[:n/2-1])[i:i+n/2] for i in range(n)]
[[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 1], [8, 9, 1, 2], [9, 1, 2, 3]]
>>>

注意:以上代码基于您的示例假设

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

如果您确实需要所有可能的值,则需要按照其他人的建议使用 itertools.permutations 或组合函数。

【讨论】:

    【解决方案2】:

    你需要的是combinations function from itertools (编辑:如果顺序很重要,请使用排列)

    请注意,此功能在 Python 2.5 中不可用。在这种情况下,您可以从上面的链接中复制代码:

    def combinations(iterable, r):
        # combinations('ABCD', 2) --> AB AC AD BC BD CD
        # combinations(range(4), 3) --> 012 013 023 123
        pool = tuple(iterable)
        n = len(pool)
        if r > n:
            return
        indices = range(r)
        yield tuple(pool[i] for i in indices)
        while True:
            for i in reversed(range(r)):
                if indices[i] != i + n - r:
                    break
            else:
                return
            indices[i] += 1
            for j in range(i+1, r):
                indices[j] = indices[j-1] + 1
            yield tuple(pool[i] for i in indices)
    

    然后

    stuff = range(9)
    what_i_want = [i for i in combinations(stuff, len(stuff)/2)]
    

    【讨论】:

    • 数字列表只是一个例子。这段代码是否适用于字符串列表?
    【解决方案3】:

    使用itertools.permutations()itertools.combinations()(取决于您是否需要,例如[1,2,3,4][4,3,2,1])和可选的第二个参数来指定长度。

    stuff = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    itertools.permutations(stuff, 4) # will return all possible lists of length 4
    itertools.combinations(stuff, 4) # will return all possible choices of 4 elements
    

    这是假设您不仅想要连续的元素。

    更新

    由于您指定不关心订单,因此您可能要查找的是itertools.combinations()

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      相关资源
      最近更新 更多