2016-11-15 25 views
0

在Python中,我如何建立一個給定2列軸的座標數組,以便輸出數組包含所有可能的座標對?如何將兩個列表轉換爲Python中的數組座標?

例如

ax1=[1,3,4] 
ax2=[a,b] 

""" 
Code that combines them 
""" 

Combined_ax1 = [1,3,4,1,3,4,1,3,4] 
Combined_ax2 = [a,a,a,b,b,b,c,c,c] 

我需要這個,所以我可以在不使用多個for循環的情況下將combined_ax1和combined_ax2提供給函數。

+0

使用'itertools.product' –

+0

看看這個:http://stackoverflow.com/questions/533905/get-the-cartesian-product-一個系列的列表在Python中 –

+4

'Combined_ax2,Combined_ax1 = zip(* itertools.product(['a','b','c'],[1,3,4]))'' (1,3,4,1,3,4,1,3,4)'和'('a','a','a','b','b','b' 'c','c','c')' – jonrsharpe

回答

2

此代碼將得到你需要

import itertools 

ax1=[1,3,4] 
ax2=['a','b'] 

Combined_ax1, Combined_ax2 = zip(*itertools.product(ax1, ax2)) 
-1

這可以通過使用列表解析如下進行:

cartesian_product = [(x, y) for x in ax1 for y in ax2] 

此代碼示例將返回包含所有可能對座標元組的列表。

相關問題