嵌套链表操作



我有一个列表,列表中的每个项目也是一个列表

所有子列表都有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'], ['10', '6']],
[['2', '4'], ['6', '2'], ['10', '6']],
[['3', '4'], ['6', '3'], ['10', '6']],
[['1', '5'], ['6', '1'], ['10', '6']],
[['2', '5'], ['6', '2'], ['10', '6']],
[['3', '5'], ['6', '3'], ['10', '6']],
[['1', '4'], ['7', '1'], ['10', '7']],
[['2', '4'], ['7', '2'], ['10', '7']],
[['3', '4'], ['7', '3'], ['10', '7']],
[['1', '5'], ['7', '1'], ['10', '7']],
[['2', '5'], ['7', '2'], ['10', '7']],
[['3', '5'], ['7', '3'], ['10', '7']]]

其中

  • 最内部列表的元素是一个只包含一个数字的字符串
  • 子列表也满足前面所述的属性

我有一个线索,这就像你必须通过每个点(本例中为六个点(并选出一个数字,选出哪个数字取决于你之前选择的对,到目前为止我还没有取得更多进展。

如果您不想生成所有组合;有效的";其中,您可以首先从列表中获取唯一的值。然后你可以得到这些的CCD_ 8(在分割字符串之后(;链接的";其中的列表:

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', '4'), ('7', '1'), ('10', '7')],
[('2', '4'), ('6', '2'), ('10', '6')],
[('2', '4'), ('7', '2'), ('10', '7')],
[('3', '4'), ('6', '3'), ('10', '6')],
[('3', '4'), ('7', '3'), ('10', '7')],
[('1', '5'), ('6', '1'), ('10', '6')],
[('1', '5'), ('7', '1'), ('10', '7')],
[('2', '5'), ('6', '2'), ('10', '6')],
[('2', '5'), ('7', '2'), ('10', '7')],
[('3', '5'), ('6', '3'), ('10', '6')],
[('3', '5'), ('7', '3'), ('10', '7')]]
import copy
lst = [['1 2 3', '4 5'], ['6 7', '1 2 3'], ['10', '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 'nnOutput:'
transformed_list = transform_list(lst)
print_list(transformed_list)

最新更新