2015-02-06 105 views
1

我想讓一個矩陣的排列,我可以評估的子集,但我有麻煩實際上使矩陣。創建一個排列矩陣

目標是取4個唯一的數字(讓我們說4 5 6 7)並找到所有的排列(4x3x2x1 = 24)並評估它們的子集。例如。一個數字將是「6475」,第一個子集是前兩個數字將是「64」,第二個子集是最後兩個數字「75」

但是我不能清理排列清單,所以我可以單獨評估每個元素。

這裏是我的代碼:

int_matrix = [] 

matrix = list(permutations([1,2,3,4])) 
int_matrix = [int(i) for i in matrix.split(",")] 

而且我得到這個錯誤:

AttributeError: 'list' object has no attribute 'split' 

輸出爲我的排列是:

[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4)..... 

我想我的問題是我」 m不能正確地從「矩陣」中刪除逗號。我應該做什麼的建議?

+0

你能告訴您的預期產出? – CoryKramer 2015-02-06 17:57:56

回答

2

您可以使用reduce()轉換您的元組爲int:

>>> [reduce(lambda x,y :x*10+y,i) for i in matrix] 
[1234, 1243, 1324, 1342, 1423, 1432, 2134, 2143, 2314, 2341, 2413, 2431, 3124, 3142, 3214, 3241, 3412, 3421, 4123, 4132, 4213, 4231, 4312, 4321] 

但是,如果你想找到你的號碼,它不是一個好的想法,並將其轉換爲int的子集!您可以使用combinations從元組grub的子集例如:

>>> from itertools import combinations 
>>> [list(combinations((1,2,3,4),i)) for i in range (1,5)] 
[[(1,), (2,), (3,), (4,)], [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)], [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)], [(1, 2, 3, 4)]] 
>>> 

但如果你只是想切你的號碼在第2部分你不需要轉換爲int,你可以使用下面的列表理解:

>>> [(i[:2],i[2:]) for i in [''.join(map(str,i)) for i in matrix]] 
[('12', '34'), ('12', '43'), ('13', '24'), ('13', '42'), ('14', '23'), ('14', '32'), ('21', '34'), ('21', '43'), ('23', '14'), ('23', '41'), ('24', '13'), ('24', '31'), ('31', '24'), ('31', '42'), ('32', '14'), ('32', '41'), ('34', '12'), ('34', '21'), ('41', '23'), ('41', '32'), ('42', '13'), ('42', '31'), ('43', '12'), ('43', '21')] 

在這種情況下,你需要你的元組轉換爲int元素爲str你可以用''.join(map(str,i)) for i in matrix做到這一點,那麼你可以加入them.and使用切片來獲取慾望的部分。

另外如果你想喲轉換爲int的部件使用map功能:如果你要分成兩個部分

>>> [map(int,(i[:2],i[2:])) for i in [''.join(map(str,i)) for i in matrix]] 
[[12, 34], [12, 43], [13, 24], [13, 42], [14, 23], [14, 32], [21, 34], [21, 43], [23, 14], [23, 41], [24, 13], [24, 31], [31, 24], [31, 42], [32, 14], [32, 41], [34, 12], [34, 21], [41, 23], [41, 32], [42, 13], [42, 31], [43, 12], [43, 21]] 

The reduce function is apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5).

+0

這似乎工作,但我需要了解如何reduce()現在的作品... – Chef1075 2015-02-06 18:04:25

+0

我將我的數字轉換爲字符串稍後在腳本中。這只是我遇到麻煩的第一部分:) – Chef1075 2015-02-06 18:05:33

+0

@ Chef1075檢查編輯。我也提出了回答鏈接 – Kasramvd 2015-02-06 18:08:58

2
l = [(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4)] 

print([int("".join(map(str,tup))) for tup in l]) 
[1234, 1243, 1324, 1342, 1423, 1432, 2134] 

out = [] 
for tup in l: 
    joined = "".join(map(str, tup)) 
    half = len(joined) // 2 
    a,b = int(joined[:half]),int(joined[half:]) 
    out.append((a,b)) 
print(out) 
[(12, 34), (12, 43), (13, 24), (13, 42), (14, 23), (14, 32), (21, 34)]