【问题标题】:How to remove the matched values in two lists separately in python?如何在python中分别删除两个列表中的匹配值?
【发布时间】:2021-05-02 03:20:20
【问题描述】:

我的 for 循环在列表方面遇到问题。 我有两个列表,如下所示。现在,如果两个列表中的名称匹配,我想删除该名称。我的代码

Input:
 col = ['cat','dog','bird','fish']
col_names= [cat,bird]
r=[]
for i in col:
    print(i)
    if i in col_names: col_names.remove(i)
    r.append(col_names)
print(r)

然后我得到这样的输出

r = [['dog','fish']] [['dog','fish']]

我想要的是:

r =['dog','bird','fish'] ['cat','dog','fish']

【问题讨论】:

  • 这是什么r =['dog','bird','fish'] ['cat','dog','fish']
  • r = [[i for i in col if i != n] for n in col_names] OR r = [list({n}.symmetric_difference(col)) for n in col_names] 请注意,最后一个选项不会保留顺序

标签: python list dataframe for-loop


【解决方案1】:

实现这一点的更简单方法是使用嵌套列表理解

>>> col = ['cat','dog','bird','fish']
>>> col_names= ['cat', 'bird']

>>> [[c for c in col if c !=cn] for cn in col_names]
[['dog', 'bird', 'fish'], ['cat', 'dog', 'fish']]

您共享的代码在逻辑上不正确。如果你想用显式的for循环来做,你可以这样写:

new_list = []
for cn in col_names:
    temp_list = []
    for c in col:
        if c != cn:
            temp_list.append(c)
    new_list.append(temp_list)

print(new_list)

【讨论】:

    【解决方案2】:

    这里的问题是每次从其中删除元素时都会编辑 col,因为它是一个指针。如果你想达到你想要的输出,你应该先创建一个副本,如下所示

    col = ['cat','dog','bird','fish']
    col_names= ['cat','bird','elephant']
    r=[]
    for name in col_names:
        tmp = col.copy() # Creates a copy of col list
        try:
            tmp.remove(name)
            r.append(tmp)
        except ValueError: # If name is not in the list
            pass # Don't do anything
    print(r)
    

    输出

    [['dog', 'bird', 'fish'], ['cat', 'dog', 'fish']]
    

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 1970-01-01
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多