H5W3
当前位置:H5W3 > 其他技术问题 > 正文

列表整合问题该怎么办?

我想把list1变成list2这样,或者把list1变成dict1,请问该怎么办?

road = ['01','02','03','04','05','06']
list1 = [
['01', '04'], ['01', '02'], ['01', '03'],
['02', '01'], ['02', '03'], ['02', '09'],['02', '08'],
['03', '01'], ['03', '06'], ['03', '02'], ['03', '04'],
['04', '01'], ['04', '05'], ['04', '03'],
['05', '06'], ['05', '04'], ['05', '07'],
['06', '05'], ['06', '07'], ['06', '08'], ['06', '03'], ['06', '02'],
]
list2 = [
['01', '04','02', '03'],
['02', '01', '03', '09', '08'],
['03', '01', '06', '02', '04'],
['04', '01', '05, '03'],
['05', '06, '04', '07'],
['06', '05', '07', '08', '03', '02']
]
dict1= {
'01':['02','03','04'],
'02':['01','03','06','08','09'],
'03':['01','02','04','06'],
'04':['01','03','05'],
'05':['04','06','07'],
'06':['02','03','05','07','08'],
}

回答

road = ['01','02','03','04','05','06']

list1 = [
['01', '04'], ['01', '02'], ['01', '03'],
['02', '01'], ['02', '03'], ['02', '09'],['02', '08'],
['03', '01'], ['03', '06'], ['03', '02'], ['03', '04'],
['04', '01'], ['04', '05'], ['04', '03'],
['05', '06'], ['05', '04'], ['05', '07'],
['06', '05'], ['06', '07'], ['06', '08'], ['06', '03'], ['06', '02'],
]

list2 = []
for i in road:
    dict1 = {}
    dict1[i] = []
    for t in list1:
        if t[0] == i:
            dict1[i].append(t[1])
    list2.append(dict1)
print(list2)

本文地址:H5W3 » 列表整合问题该怎么办?

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址