【问题标题】:How to compare two lists and print non shared values [duplicate]如何比较两个列表并打印非共享值
【发布时间】:2020-10-16 05:39:59
【问题描述】:

我正在尝试编写一个简单的程序,它只运行一个字符串列表,并将每个字符串与包含一些相同单词的较短字符串列表进行比较。然后我想打印出长列表中不在短列表中的所有单词。我认为我有正确的逻辑,但我似乎无法让打印工作。这是我所拥有的:

oneList = ['egg', 'duck', 'cow']
twoList = ['egg', 'giraffe', 'cow', 'poo', 'speaker']

for twoString in twoList:
    for oneString in oneList:
        if (twoList[twoTicker] = oneList[oneTicker]):
            #do nothing
        else:
            #do nothing
    #if it reaches end of list and isnt there, print word.

【问题讨论】:

    标签: python list loops


    【解决方案1】:
    • 这回答了所写的问题。
      • 遍历字符串列表并将每个字符串与包含一些相同单词的较短字符串列表进行比较
      • 打印出长列表中不在短列表中的所有单词

    使用Membership test operations

    • 使用not in
      • in 检查一个值是否属于另一个值。
      • 在这种情况下,如果b 中的值不在a 中,则打印它。
    a = ['egg', 'duck', 'cow']
    b = ['egg', 'giraffe', 'cow', 'poo', 'speaker']
    
    for v in b:
        if v not in a:
            print(v)
    
    
    giraffe
    poo
    speaker
    

    使用list-comprehension

    result = [v for v in b if v not in a]
    
    print(result)
    
    ['giraffe', 'poo', 'speaker']
    

    使用set

    set(b) - set(a)
    
    {'giraffe', 'poo', 'speaker'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-25
      • 2015-01-25
      • 2013-04-25
      • 2019-05-15
      • 2016-01-01
      • 2020-12-13
      • 2015-01-24
      • 2020-12-29
      相关资源
      最近更新 更多