我正在使用itertools.combinations
來匹配列表的所有可能組合。Python距離中的itertools組合
我的列表看起來像
[[1,2],[2,3],[3,4],[4,5],[5,6]]
我知道如何讓所有的組合,但如果我想使用的距離公式對每一個組合我怎麼會去這樣做?
我不知道如何在這個問題上使用每個組合。
我正在使用itertools.combinations
來匹配列表的所有可能組合。Python距離中的itertools組合
我的列表看起來像
[[1,2],[2,3],[3,4],[4,5],[5,6]]
我知道如何讓所有的組合,但如果我想使用的距離公式對每一個組合我怎麼會去這樣做?
我不知道如何在這個問題上使用每個組合。
只需環在combinations()
函數的輸出:
for xy1, xy2 in combinations(inputlist, 2):
distance = calculate_distance(xy1, xy2)
這使用元組拆包; combinations
每個產生兩個元素的元組,Python將這些分配給這兩個名稱。產生第一組合是([1, 2], [2, 3])
,但循環分配這些到xy1
(設置爲[1, 2]
和xy2
(設置爲[2, 3]
)分別
快速演示只是打印:
>>> from itertools import combinations
>>> inputlist = [[1,2],[2,3],[3,4],[4,5],[5,6]]
>>> for xy1, xy2 in combinations(inputlist, 2):
... print(xy1, xy2)
...
[1, 2] [2, 3]
[1, 2] [3, 4]
[1, 2] [4, 5]
[1, 2] [5, 6]
[2, 3] [3, 4]
[2, 3] [4, 5]
[2, 3] [5, 6]
[3, 4] [4, 5]
[3, 4] [5, 6]
[4, 5] [5, 6]
當我的組合形式如下: ([1,2],[2,3]) 我如何進入你的表單? –
@BobDarren:仔細看看'for'循環;它使用元組解包,有*兩個*名稱分配給。 Python解壓縮'([1,2],[2,3])元組,並按順序將每個元素分配給一個名稱。 –
只要迭代組合
def calculate_distance(points):
[[x1, y1], [x2, y2]] = points
return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
inputlist = [[1,2],[2,3],[3,4],[4,5],[5,6]]
distances = [calculate_distance(points) for points in combinations(inputlist, 2)]
假設你以後想要以一種有意義的方式訪問這些數據,我可能會提出一個字典理解。類似於Martjin的sol但有一點添加的上下文:
distance = {tuple(combo): distance(combo) for combo in combinations(inputlist, 2)}
元組轉換的原因是爲了確保字典的關鍵字是不可變的。
不完全知道你在尋找什麼,但對於距離方程潛力將是這樣的:
def distance(combo):
return math.sqrt(combo[0]**2+combo[1]**2)
什麼是你到目前爲止的代碼?簡單地遍歷'itertools.combinations()'的輸出來獲取每個生成的組合。 –