您可以使用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).
你能告訴您的預期產出? – CoryKramer 2015-02-06 17:57:56