作者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://webptt.com/cn.aspx?n=bbs/Python/M.1516678038.A.BED.html
1F:推 vi000246: loop list1 如果list2没有这个元素就补上-- 01/23 11:40
2F:推 vfgce: d=dict(list2) 01/23 13:58
3F:→ vfgce: c=[[x,d.get(x)] if d.get(x) else ['--','--'] for x in\ 01/23 13:59
4F:→ vfgce: list1]] 01/23 13:59
5F:→ vfgce: print(c) 01/23 13:59
6F:→ giftedguilt: 非常感谢! 01/23 18:59