亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢查多維列表的一部分是否在單獨的多維列表中

檢查多維列表的一部分是否在單獨的多維列表中

千巷貓影 2022-10-18 15:04:50
這是一些示例代碼。list1 = [['one','a'],['two','a'],['three','a'],['four','a']]list2 = [['three','b'],['four','a'],['five','b']]for l in list1:    if l not in list2:        print(l[0])以及此代碼的輸出。onetwothree因為['four','a']確實出現在兩個列表中。我要做的是檢查第一個列表中每個條目的第一項是否出現在第二個列表中,我嘗試了以下變體list1 = [['one','a'],['two','a'],['three','a'],['four','a']]list2 = [['three','b'],['four','a'],['five','b']]for l in list1:    if l[0] not in list2:        print(l[0])但是,該代碼返回onetwothreefour盡管“三”和“四”都出現在第二個列表中。我之前使用過不同的方法來查找僅出現在一對列表中的一個中的值,然后用它來制作一個包含所有可能值且沒有重復的主列表,我相信使用這種方法應該可以做到這一點,但是語法對我來說是個謎。我在這里哪里出錯了?
查看完整描述

2 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

您可以使用not any(),然后檢查理解中的特定要求:


list1 = [['one','a'],['two','a'],['three','a'],['four','a']]

list2 = [['three','b'],['four','a'],['five','b']]


for l in list1:

    if not any(l[0] == l2[0] for l2 in list2):

        print(l[0])


# one

# two

如果順序無關緊要,您也可以使用集合:


list1 = [['one','a'],['two','a'],['three','a'],['four','a']]

list2 = [['three','b'],['four','a'],['five','b']]


set(l[0] for l in list1) - set(l2[0] for l2 in list2)

# {'one', 'two'}


查看完整回答
反對 回復 2022-10-18
?
達令說

TA貢獻1821條經驗 獲得超6個贊

您可以使用set operations


list1 = [['one','a'],['two','a'],['three','a'],['four','a']]

list2 = [['three','b'],['four','a'],['five','b']]


result = set(i[0] for i in list1) - set(i[0] for i in list2)


print(result)


# output {'one', 'two'}


查看完整回答
反對 回復 2022-10-18
  • 2 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號