你这里有几个不同的方法来解决这个问题:
perm2 = [int(''.join(str(i) for i in sublist)) for sublist in perm]
2.perm2 = [int(''.join(map(str, sublist))) for sublist in perm]
更高性能数学版:
3.print [reduce(lambda x, y: 10 * x + y, sublist) for sublist in perm]
4.print map(lambda x: reduce(lambda x, y: 10 * x + y, x), perm)
此方法的列表转换成这种形式的字符串 - >例:[1, 2, 3, 4, 5]
首先使用repr()
然后切片返回子列表。
5.print [int(repr(sublist)[1::3]) for sublist in perm]
样本输出:
>>> import itertools
>>> digits = [1,2,3,0,0]
>>> perm = list(itertools.permutations(digits))
>>> perm2 = [int(''.join(map(str, sublist))) for sublist in perm]
>>> print perm2
[12300, 12300, 12030, 12003, 12030, 12003, 13200, 13200, 13020, 13002, 13020, 13002, 10230, 10203, 10320, 10302, 10023, 10032, 10230, 10203, 10320, 10302, 10023, 10032, 21300, 21300, 21030, 21003, 21030, 21003, 23100, 23100, 23010, 23001, 23010, 23001, 20130, 20103, 20310, 20301, 20013, 20031, 20130, 20103, 20310, 20301, 20013, 20031, 31200, 31200, 31020, 31002, 31020, 31002,0,0, 32010, 32001, 32010, 32001, 30120, 30102, 30210, 30201, 30012, 30021, 30120, 30102, 30210, 30201, 30012, 30021, 1230, 1203, 1320, 1302, 1023, 1032, 2130, 2103, 2310, 2301, 2013, 2031, 3120, 3102,, 3201, 3012, 3021, 123, 132, 213, 231, 312, 321, 1230, 1203, 1320, 1302, 1023, 1032, 2130, 2103, 2310, 2301, 2013, 2031, 3120, 3102,, 3201, 3012, 3021, 123, 132, 213, 231, 312, 321]
一些基准:
from timeit import timeit
repeat = 1000000
print 'Solution 1 took ->', timeit("import itertools;[int(''.join(str(i) for i in sublist)) for sublist in list(itertools.permutations([1,2,3,0,0]))]", number=repeat), 'secs'
print 'Solution 2 took ->', timeit("import itertools;[int(''.join(map(str, sublist))) for sublist in list(itertools.permutations([1,2,3,0,0]))]", number=repeat), 'secs'
print 'Solution 3 took ->', timeit("import itertools;map(lambda x: reduce(lambda x, y: 10 * x + y, x), list(itertools.permutations([1,2,3,0,0])))", number=repeat), 'secs'
print 'Solution 4 took ->', timeit("import itertools;[reduce(lambda x, y: 10 * x + y, sublist) for sublist in list(itertools.permutations([1,2,3,0,0]))]", number=repeat), 'secs'
print 'Solution 5 took ->', timeit("import itertools;[int(repr(sublist)[1::3]) for sublist in list(itertools.permutations([1,2,3,0,0]))]", number=repeat), 'secs'
结果(重复= 1000000):
Solution 1 took -> 242.802856922 secs
Solution 2 took -> 153.20646596 secs
Solution 3 took -> 97.4842221737 secs
Solution 4 took -> 87.8391051292 secs
Solution 5 took -> 122.897110224 secs
提示:12300 = 1 * 10000 + 2 * 1000 + 3 * 100 + 0 * 10 + 0 –