如何连接从python permutations()返回的数字?

时间:2013-10-06 18:42:55

标签: python

我有以下代码生成0-9范围内的所有2位数排列:

p = permutations(range(10), 2)

产生如下结果:

  

(0,1); (0,2); (0,3); (0,4); (0,5); (0,6); (0,7); (0,8); (0,9); (1,0); (1,2); (1,3); (1,4); (1,5); (1,6); (1,7); (1,8); (1,9); (2,0); (2,1); (2,3); (2,4); (2,5); (2,6); (2,7); (2,8); (2,9); (3,0); (3,1); (3,2); (3,4); (3,5); (3,6); (3,7); (3,8); (3,9); (4,0); (4,1); (4,2); (4,3); (4,5); (4,6); (4,7); (4,8); (4,9); (5,0); (5,1); (5,2); (5,3); (5,4); (5,6); (5,7); (5,8); (5,9); (6,0); (6,1); (6,2); (6,3); (6,4); (6,5); (6,7); (6,8); (6,9); (7,0); (7,1); (7,2); (7,3); (7,4); (7,5); (7,6); (7,8); (7,9); (8,0); (8,1); (8,2); (8,3); (8,4); (8,5); (8,6); (8,7); (8,9); (9,0); (9,1); (9,2); (9,3); (9,4); (9,5); (9,6); (9,7); (9,8)

如何获得[01,02,03....98]之类的输出然后我可以通过调用p [0]来获取某个元素?

6 个答案:

答案 0 :(得分:2)

只汇总每个结果:

p = permutations(range(10), 2)
result = [str(x[0]) + str(x[1]) for x in p]

答案 1 :(得分:2)

A(可能不是最有效的)单行:

["".join([str(x) for x in elem]) for elem in p]

或者:

[("%d"*len(p[0]))%(elem) for elem in p]

答案 2 :(得分:2)

In [13]: import itertools as IT
In [17]: p = IT.permutations(range(10), 2)

In [18]: list(IT.starmap('{}{}'.format, p))
Out[18]: 
['01',
 '02',
 '03',
 '04',
...

答案 3 :(得分:1)

使用列表理解:

p = permutations(range(10), 2)
result = [ "%d%d" % (x[0], x[1]) for x in p ]

答案 4 :(得分:1)

正如John Clements和我在评论中指出的那样,它可以在不进行排列的情况下制作你想要的字符串或数字。

数字0到9的两个排列简单地表示从1到98的没有任何重复数字的整数。方便的是,所有带有重复数字的2位数字都是11的倍数,因此您可以轻松地制作列表理解或生成器表达式,跳过您不想要的数据:

nums = [i for i in range(1, 99) if i % 11]

如果你希望你的结果是一个双字符串的列表,你可以使用format函数和一个格式字符串来表示用一个数字填充一个零的数字:

strings = [format(i, '02') for i in range(1, 99) if i % 11]

不幸的是,将这种技术扩展到更长的数字有点困难,因为只要跳过11的倍数就不会再削减它了。最好的方法可能取决于你实际使用的价值所做的事情。

答案 5 :(得分:0)

这有效:

>>> from itertools import permutations
>>> ["%i%i" % (a,b) for a,b in permutations(range(10), 2)]
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '12', '13', '14', '15',
'16', '17', '18', '19', '20', '21', '23', '24', '25', '26', '27', '28', '29', '30', 
'31', '32', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '45', '46', 
'47', '48', '49', '50', '51', '52', '53', '54', '56', '57', '58', '59', '60', '61', 
'62', '63', '64', '65', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', 
'78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '89', '90', '91', '92', 
'93', '94', '95', '96', '97', '98']
>>>

或者,如果你想要它们作为整数,你可以这样做:

>>> from itertools import permutations
>>> [int("%i%i" % (a, b)) for a,b in permutations(range(10), 2)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 
26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 
49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 
72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 
95, 96, 97, 98]
>>>

但请注意,Python不允许您使用以0开头的整数。