[英]Python list comprehension to return edge values of a list
如果我在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]
是否有一些列表理解代碼我可以用來迭代列表並檢索所有這些子列表? 我不關心列表中值的順序,我只是想找到一個生成列表的聰明方法。
你需要的是來自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)]
>>> 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或組合函數。
使用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()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.