如何在Python中从列表中创建嵌套列表,其中列表的特定值匹配

afdcj2ne  于 2023-04-08  发布在  Python
关注(0)|答案(2)|浏览(109)

这里我需要得到列表的嵌套列表,其中值为'01 T-01 W',直到下一次出现该值

actual value=['01T - 01W','01T - 02W', '01T - 03W', '02T - 01W', '02T - 02W', '02T - 03W','01T - 01W', '01T - 02W','01T - 01W', '01T - 02W','01T - 01W', '01T - 02W', '01T - 03W', '02T - 01W', '02T - 02W', '02T - 03W']
my requirement=
[['01T - 01W','01T - 02W', '01T - 03W', '02T - 01W', '02T - 02W', '02T - 03W'],
['01T - 01W', '01T - 02W'], 
['01T - 01W', '01T - 02W'], 
['01T - 01W', '01T - 02W', '01T - 03W', '02T - 01W', '02T - 02W', '02T - 03W']]
u7up0aaq

u7up0aaq1#

使用for循环遍历列表,并在每次遇到值“01 T-01 W”时创建一个子列表

for v in value:
    sublist.append(v)
    if v == '01T - 01W':
        requierement.append(sublist)
        sublist = []
requirement.append(sublist) #to append the last sublist to the result
nbnkbykc

nbnkbykc2#

def create_nested_packages(duct_ids, desired_value):
    nested_list = []
    sublist = []
    for item in duct_ids:
        if item == desired_value:
            if sublist:
                nested_list.append(sublist)
                sublist = []
        else:
            sublist.append(item)
    if sublist:
        nested_list.append(sublist)
    count=1
    for i in nested_list:
        i.insert(0,desired_value)
        i.insert(0,'Package '+str(count))
        count+=1
    print(nested_list)
    return nested_list

相关问题