【问题标题】:Create sublist of a list containing tuples and list with starting and end elements of sublist as tuples创建包含元组的列表的子列表,并以子列表的开始和结束元素作为元组的列表
【发布时间】:2018-10-20 12:27:14
【问题描述】:

我有一个像这样的列表

[(1.0, 1.5), [2, 2], (1.5, 1.0), (1.1428571343421936, 0.28571426868438721), [1, 0], (0.5, 0.0), (0.66666668653488159, 0.0), [0, 0], [0, 1], (0.5, 1.25)]

我想通过将元组元素附加为子列表的第一个和最后一个元素来创建子列表,如下所示:

[[(1.0, 1.5), [2, 2], (1.5, 1.0)],[(1.1428571343421936,
0.28571426868438721), [1, 0], (0.5, 0.0)],[(0.66666668653488159, 0.0), [0, 0], [0, 1], (0.5, 1.25)]]

我尝试使用以下代码,但它似乎不起作用,因为我无法弄清楚如何以我想要的方式选择元组。它也给出了索引错误。

full_list = []
for ind,value in enumerate(flat_list):
    if isinstance(value,(tuple)):
        a = []
        a.append(value)
        temp = 0
        while(temp!=1):
            ind = ind + 1
            j = flat_list[ind]
            a.append(j)
            if type(j) == 'tuple':
                temp = 1
            break
        full_list.append(a)
    else:
        continue

print(full_list)

请提出一些建议!!

【问题讨论】:

    标签: python python-2.7 list tuples


    【解决方案1】:

    break 作为while 循环的最后一条语句,可以替换为if

    full_list = []
    state = 0
    for value in flat_list:
        if isinstance(value, tuple):
            if state == 0:
                state = 1
                inner_list = []
                full_list.append(inner_list)
            else:
                state = 0
        inner_list.append(value)
    
    print(full_list)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 2021-09-22
      • 2019-04-21
      • 1970-01-01
      • 2019-08-23
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      相关资源
      最近更新 更多