2017-06-04 76 views
2

下面的python代码为我提供了给定值的不同组合。将此python代码的输出更改为列表?

import itertools 

iterables = [ [1,2,3,4], [88,99], ['a','b'] ] 
for t in itertools.product(*iterables): 
    print t 

输出: -

(1, 88, 'a') 
(1, 88, 'b') 
(1, 99, 'a') 
(1, 99, 'b') 
(2, 88, 'a') 

等。

有人可以告诉我如何修改此代码,使输出看起来像一个列表;

188a 
188b 
199a 
199b 
288a 
+2

您的输出看起来不像列表。推测你的意思是输出不应该看起来像元组,而只是*加入*? –

回答

5

你必须将数字转换为字符串,然后再加入结果:

print ''.join(map(str, t)) 

你可能避免,如果你转换让您的输入字符串开头:

iterables = [['1', '2', '3', '4'], ['88', '99'], ['a', 'b']] 
for t in itertools.product(*iterables): 
    print ''.join(t) 

如果你想要的是打印的值加在一起(而不是与他们做任何事,否则),然后使用print()的功能(通过使用from __future__ import print_function Python 2的功能开关或使用Python 3):

from __future__ import print_function 

iterables = [[1, 2, 3, 4], [88, 99], ['a', 'b']] 
for t in itertools.product(*iterables): 
    print(*t) 
5

你可以试试这个:

iterables = [ [1,2,3,4], [88,99], ['a','b'] ] 

new_list = [''.join(map(str, i)) for i in itertools.product(*iterables)] 
+0

为什么地图中的“列表”?只要做'map(str,i)' – rassar

+0

@rassar:在Python 2中,是的,在Python 3中不是这样(因为'str.join()'对于列表输入工作更快)。 –