【问题标题】:Compare the values of one list with the values of another listCompare the values of one list with the values of another list
【发布时间】:2022-12-01 22:40:52
【问题描述】:

I have the lista:

a = ['wood', 'stone', 'bricks', 'diamond']

And the listb:

b = ['iron', 'gold', 'stone', 'diamond', 'wood']

I need to compare lists and if value of listaequals with value from listb, it will be added to a listc:

c = ['wood', 'stone', 'diamond']

How can I compare these lists?

【问题讨论】:

标签: python list compare


【解决方案1】:

You could convert them to sets and get the intersection.

list(set(a) & set(b))

【讨论】:

    【解决方案2】:

    When comparing values of one list to another you can use one of two options:

    First you could use a for loop like so:

    c = []
    
    for element in a:
        if element in b:
            c.append(element)
    print(c)
    

    This is a rather chunky way of doing it, rather you could just use a comprehension like so:

    c = [element for element in a if element in b]
    print(c)
    

    Both of these answers give the output of:

    ['wood', 'stone', 'diamond']

    Hope this helps.

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-01
      • 2022-12-02
      • 2022-12-28
      • 2017-03-22
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      相关资源
      最近更新 更多