[問題] 比對兩個串列,缺少的項目加上'--'

看板Python作者時間7年前 (2018/01/23 11:27), 編輯推噓2(204)
留言6則, 3人參與, 7年前最新討論串1/1
先感謝各位撥空進來看這篇 如題,網路上嘗試過各種關鍵字組合,都找不到有人問過類似的問題 目前我有比對兩個串列的需求,大概像這樣: list1 = ['a', 'b', 'c', 'd', 'e', 'f'] list2 = [['a', 1], ['b', 2], ['d', 4], ['e', 5]] 如果我想要比對兩個串列,讓list2缺少的'c', 'f'兩項補上變成 list2 = [['a', 1], ['b', 2], ['--', '--'], ['d', 4], ['e', 5], ['--', '--']] 請問應該如何處理? 作為一個初學者,目前我想到的語法實在錯誤不少而且不合python語法邏輯: for index in list1 and for item in list 2: if list2[item][0] != list1[index]: list2.insert(index, ['--', '--']) 可以一眼看出以上語法是不正確的... 還請各位高手幫忙指點迷津,非常感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.41.156.117 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1516678038.A.BED.html

01/23 11:40, 7年前 , 1F
loop list1 如果list2沒有這個元素就補上--
01/23 11:40, 1F

01/23 13:58, 7年前 , 2F
d=dict(list2)
01/23 13:58, 2F

01/23 13:59, 7年前 , 3F
c=[[x,d.get(x)] if d.get(x) else ['--','--'] for x in\
01/23 13:59, 3F

01/23 13:59, 7年前 , 4F
list1]]
01/23 13:59, 4F

01/23 13:59, 7年前 , 5F
print(c)
01/23 13:59, 5F

01/23 18:59, 7年前 , 6F
非常感謝!
01/23 18:59, 6F
文章代碼(AID): #1QPgkMlj (Python)
文章代碼(AID): #1QPgkMlj (Python)