我有一些字符串包含由空格字符分隔的许多值。有时我们可以找到一个由许多值组成的值,这些值由字符“,”分隔,例如在下面的字符串中,值3和5由分别用逗号分隔的2和4个值组成。
value1 value2 value3_0,value3_1 value4 value5_0,value5_1,value5_2,value5_3 value6
我想将此字符串拆分为多个字符串,以便字符串中没有组合值。所以前面的字符串变为:
value1 value2 value3_0 value4 value5_0 value6
value1 value2 value3_1 value4 value5_1 value6
value1 value2 value3_0 value4 value5_2 value6
value1 value2 value3_1 value4 value5_3 value6
value1 value2 value3_0 value4 value5_1 value6
value1 value2 value3_1 value4 value5_2 value6
value1 value2 value3_0 value4 value5_3 value6
value1 value2 value3_1 value4 value5_0 value6
如何在python中轻松实现?
编辑:在输入字符串中,有一个组件“value3_0,value3_1”(该组件由2个值组成),我们有“value5_0,value5_1,value5_2,value5_3”(此组件由4个值组成),所以我们将有2 * 4 = 8个新字符串,其中没有组合成分。
答案 0 :(得分:3)
怎么样:
from itertools import product
text = 'value1 value2 value3_0,value3_1 value4 value5_0,value5_1,value5_2,value5_3 value6'
items = [el.split(',') for el in text.split()]
for item in product(*items):
print item # use ' '.join(item) to get a string back
输出:
('value1', 'value2', 'value3_0', 'value4', 'value5_0', 'value6')
('value1', 'value2', 'value3_0', 'value4', 'value5_1', 'value6')
('value1', 'value2', 'value3_0', 'value4', 'value5_2', 'value6')
('value1', 'value2', 'value3_0', 'value4', 'value5_3', 'value6')
('value1', 'value2', 'value3_1', 'value4', 'value5_0', 'value6')
('value1', 'value2', 'value3_1', 'value4', 'value5_1', 'value6')
('value1', 'value2', 'value3_1', 'value4', 'value5_2', 'value6')
('value1', 'value2', 'value3_1', 'value4', 'value5_3', 'value6')