在子列表的开头和结尾创建包含元组的列表的列表

时间:2018-10-24 10:10:17

标签: python python-2.7 list tuples

我有一个扁平化的列表,诸如此类

l = [(2.0000001192092896, 3.3999999761581421), [4, 3], (1.9999999701976776, 1.7999999821186066), (0.875, 1.125), [-1, 0], [-1, 4], (1.5, 3.5)].

我想在开头和结尾创建一个包含元组的列表列表:

l' = [[(2.0000001192092896, 3.3999999761581421), [4, 3], (1.9999999701976776, 1.7999999821186066)],[(1.9999999701976776, 1.7999999821186066),(0.875, 1.125)], [(0.875, 1.125), [-1, 0], [-1, 4], (1.5, 3.5)],[(1.5, 3.5),(2.0000001192092896, 3.3999999761581421)]]

l'包含所有元组以及它们之间的列表(如果有)。

我正尝试使用以下代码执行相同操作,但无法成功实现:

full_list = []
state = 0
for ind,value in enumerate(l):
    if isinstance(value, tuple):
        if state == 0:
            state = 1
            inner_list = []
            if ind == len(l) - 1:
                k = 0
            else:
                k = ind + 1
            j = l[k]
            if isinstance(j,tuple):
                full_list.append(inner_list)
                inner_list.append(j)
        else:
            state = 0 
    inner_list.append(value)     

print(full_list)   

有人可以建议其他选择吗?

2 个答案:

答案 0 :(得分:0)

获取存在tuples的索引,然后zip进行索引,并使用列表理解为:

tup_index = [index for index,value in enumerate(l) if isinstance(value,tuple)]
full_list = [l[first:last+1] for first,last in zip(tup_index[::2],tup_index[1::2])]

print(full_list)

[[(2.0000001192092896, 3.399999976158142),[4, 3],(1.9999999701976776, 1.7999999821186066)],
 [(0.875, 1.125), [-1, 0], [-1, 4], (1.5, 3.5)]]

或者如果列表中包含奇数个元组,则:

if len(tup_index)%2==0:
    full_list = [l[first:last+1] for first,last in zip(tup_index[::2],tup_index[1::2])]
else:
    tup_index.append(len(l)+1)
    full_list = [l[first:last+1] for first,last in zip(tup_index[::2],tup_index[1::2])]

答案 1 :(得分:0)

这似乎可以清理一些东西。无需检查是否为列表,因为只有元组并且也以这种方式列出。

l = [(2.0000001192092896, 3.3999999761581421), [4, 3], (1.9999999701976776, 1.7999999821186066), (0.875, 1.125), [-1, 0], [-1, 4], (1.5, 3.5)]
full_list = []
inner_list = []
for value in l:
    if isinstance(value, tuple):
        inner_list.append(value)
        if len(inner_list) > 0:
            full_list.append(inner_list)
            inner_list = []
    else:
        inner_list.append(value)

print(full_list)

这将打印:

[[(2.0000001192092896, 3.399999976158142), [4, 3], (1.9999999701976776, 1.7999999821186066)], [(0.875, 1.125), [-1, 0], [-1, 4], (1.5, 3.5)]]