作者giftedguilt ()
看板Python
標題[問題] 比對兩個串列,缺少的項目加上'--'
時間Tue Jan 23 11:27:15 2018
先感謝各位撥空進來看這篇
如題,網路上嘗試過各種關鍵字組合,都找不到有人問過類似的問題
目前我有比對兩個串列的需求,大概像這樣:
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
推 vi000246: loop list1 如果list2沒有這個元素就補上-- 01/23 11:40
推 vfgce: d=dict(list2) 01/23 13:58
→ vfgce: c=[[x,d.get(x)] if d.get(x) else ['--','--'] for x in\ 01/23 13:59
→ vfgce: list1]] 01/23 13:59
→ vfgce: print(c) 01/23 13:59
→ giftedguilt: 非常感謝! 01/23 18:59