如何比较两个不同对象的列表并返回匹配项?

时间:2019-12-19 12:38:00

标签: python list object

我想拿这两个列表进行比较,

list1 = [(Joe Black, married, happy),(Mili Cis, unmarried , happy),(Gary Oldman, married, unhappy)]
list2 = [Joe Black,Gary Oldman]

我想要一个新列表:

list3 = [(Joe Black, married, happy),(Gary Oldman, married, unhappy)]

对对象的引用来自list1。

6 个答案:

答案 0 :(得分:1)

如果您打算发布此代码:

<b-button v-for="button in this.buttons" @click="button.click(m_this)" :key="button.label"> {{ button.label }} </b-button>

这就是您想要的列表理解:

list1 = [('Joe Black', 'married', 'happy'), ('Mili Cis', 'unmarried', 'happy'), ('Gary Oldman', 'married', 'unhappy')]
list2 = ['Joe Black', 'Gary Oldman']

输出:

list3 = [(name,status,desc) for (name,status,desc) in list1 if name in list2]

print(list3)

答案 1 :(得分:1)

常规方法:

list1 = [("Joe Black", "married", "happy"),("Mili Cis", "unmarried" , "happy"),("Gary Oldman", "married", "unhappy")]
list2 = ["Joe Black","Gary Oldman"]
a = []
for i in list1:
    if i[0] in list2:
        a.append(i)
print(a)

输出:

[('Joe Black', 'married', 'happy'), ('Gary Oldman', 'married', 'unhappy')]

使用列表理解:

list1 = [("Joe Black", "married", "happy"),("Mili Cis", "unmarried" , "happy"),("Gary Oldman", "married", "unhappy")]
list2 = ["Joe Black","Gary Oldman"]
a = [i for i in list1 if i[0] in list2]
print(a)

输出:

[('Joe Black', 'married', 'happy'), ('Gary Oldman', 'married', 'unhappy')]

答案 2 :(得分:1)

尝试以下操作:list3 = [x for x in list1 if x[0] in list2]

答案 3 :(得分:0)

我将假定名称是此答案的字符串。

list1 = [(Joe Black, married, happy),(Mili Cis, unmarried , happy),(Gary Oldman, married, unhappy)]
list2 = [Joe Black,Gary Oldman]
list3 = []
for name in list2:
  for person in list1:
    if name ==  person[0]:
      list3.append(person)

答案 4 :(得分:0)

直接解决方案:

list3 = [x for x in list1 if x[0] in list2]

答案 5 :(得分:0)

因此,基本上,您想做的是对列表2中的名称进行迭代,然后检查列表1的子列表中列表2中的名称是否存在

theta