[英]python: getting all pairs of values from list
我想要一個列表中每對值的元組,例如
[1,2,3,4]
會產生:
(1,2)
(1,3)
(1,4)
(2,3)
(2,4)
(3,4)
這似乎很單線的食譜,但我不能讓它發揮作用。
這實際上是列表中2個元素的組合。 通過以下方式使用itertools.combinations
:
>>> your_list = [1,2,3,4]
>>> from itertools import combinations
>>> list(combinations(your_list,2))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
如果需要所有對,請使用itertools.product
如果你想避免使用索引訪問列表元素,一種更 Pythonic 的方法如下:
lst = [1,2,3,4]
listOfPairs = []
for e1 in lst:
for e2 in lst:
if e1 >= e2: continue #Flip sign for descending order
listOfPairs.append((e1, e2))
假設您不能在列表的元素上使用<
<=
>
>=
比較器,例如在函數列表中,您可以調用.index()
function (根據列表順序排序):
#Some nonsense example functions
def f1(): return
def f2(): return
def f3(): return
def f4(): return
lst = [f1, f2, f3, f4]
listOfPairs2 = []
for e1 in lst:
for e2 in lst:
if lst.index(e1) >= lst.index(e2): continue
listOfPairs2.append((e1, e2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.