问题描述
我有一个列表,列表中的每个项目也是一个列表
所有子列表都有2个元素,并且它们链接在一起,
[l1,l2,l3,l4...]
它们链接在一起的方式是l2[-1]
等于l1[0]
,l3[-1]
等于l2[0]
,l4[-1]=l3[0]
,等等。
所有子列表都具有字符串元素,例如'1 2 3'
(由空格分隔的多个唯一数字)或'7'
(仅一个数字)。
我想对下面的列表进行转换
[['1 2 3','4 5'],['6 7','1 2 3'],['10','6 7']]
输出为
[[['1','4'],['6','1'],'6']],[['2','2'],[['3','3'],[['1','5'],['7','7']],'7']]]
其中
- 最里面的列表的元素是一个只包含一个数字的字符串。
- 子列表还满足前面所述的属性。
我有一个线索,就像您必须通过每个点(在示例中为六个点)并选择一个数字,要选择哪个数字取决于您之前选择的那对,所以我没有取得更大的进步,所以远。
解决方法
如果您不想生成所有组合,然后选择“有效”组合,则可以首先从列表中仅获取唯一值。
然后,您可以获取其中的itertools.product
(在拆分字符串之后),然后从其中重建“链接”列表:
lst = [['1 2 3','4 5'],['6 7','1 2 3'],['10','6 7']]
sub = [lst[0][1]] + [x[0] for x in lst] # ['4 5','1 2 3','6 7','10']
res = [ [(b,a) for a,b in zip(p,p[1:])] for p in product(*map(str.split,sub))]
我在这里使用元组而不是嵌套列表,只是为了便于理解复杂的列表,请随时用更多的(...)
替换[...]
。结果:
[[('1','4'),('6','1'),('10','6')],[('1',('7','7')],[('2','2'),[('3','3'),'5'),'7')]]
,
import copy
lst = [['1 2 3','6 7']]
def print_list(ls):
if ls is not None:
for x in ls:
print x
def transform_list(l):
if(len(l)==0):
print 'list provided is empty'
return None
tr=[] # intermediate transformed list
for b in l[0][-1].split(' '):
for a in l[0][0].split(' '):
tr = tr + [[[a,b]]]
for i in range(1,len(l)):
new_tr = []
for a in l[i][0].split(' '):
temp_tr=copy.deepcopy(tr)
for t in range(len(temp_tr)):
temp_tr[t].append( [a,temp_tr[t][-1][0]] )
new_tr = new_tr + temp_tr
tr=copy.deepcopy(new_tr)
return tr
print '\n\nOutput:'
transformed_list = transform_list(lst)
print_list(transformed_list)