【问题标题】:Python- Find unmatched values from multiple lists [closed]Python-从多个列表中查找不匹配的值[关闭]
【发布时间】:2017-01-26 15:48:19
【问题描述】:

我是 python 新手,想听听您对我的函数的建议。我想做的如下。

我有 2 个列表 A 和 B。(例如 A = [1,2,3,4,5], B = [4,3,2,1])我想创建一个在列表 B 中不存在的 A。所以在这种情况下为 5。

我在下面写了一个函数,但它不起作用,我无法弄清楚代码中有什么问题......谁能帮我理解错误是什么?这似乎很容易,但对我来说很难。谢谢你的帮助!!

def finder(arr1,arr2):
    arr1 = sorted(arr1)
    arr2 = sorted(arr2)

    eliminated = []

    for x in arr1:
        if x not in arr2:
            eliminated = eliminated.append(x)
        else:
            pass
    return eliminated

【问题讨论】:

  • 把这个eliminated = eliminated.append(x)改成这个eliminated.append(x)
  • frozenset(a) - frozenset(b) -- 这将产生一个可用作可迭代的不可变集合,它将包含 a 中不在 b 中的所有项目。请注意,副作用是 ab 中的任何重复项将不存在,也不会保留顺序。
  • 设置差异是解决这个问题的方法,因为它在in O(n^2) 解决方案面前弯曲它的 O(n) 肌肉:D。

标签: python arrays list python-2.7 missing-data


【解决方案1】:

.append() 方法将修改原始列表。更改以下行

eliminated = eliminated.append(x)

eliminated.append(x)

您也不需要对列表进行排序。

【讨论】:

  • 谢谢!正如你所说,我改变了我的代码。但是该功能仍然不起作用。它没有返回任何东西......有什么想法吗?
  • @yusuke0426 您很可能没有打印方法调用的返回。简单地调用你的方法不会输出任何东西。您正在返回您的结果,但实际上并没有打印任何内容。只需在您的方法调用周围调用 print
  • @yusuke0426 适合我:repl.it/Dc1p
  • @idjaw 你是对的!在我写完 print(finder(A,B)) 之后,它起作用了!但是为什么简单地调用该方法不打印任何东西呢?我认为函数本身会返回消除列表中的值...
  • @yusuke0426 从方法中返回一些东西并不意味着它会被打印出来。您必须明确打印您想要在程序中显示的内容。
【解决方案2】:

这里有三种不同的方法。第一种方式使用集合差异,第二种使用内置过滤器功能,第三种使用列表推导式。

Python 2.7.12 (default, Jul  9 2016, 12:50:33)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> A=[1,2,3,4,5]
>>> B=[4,3,2,1]
>>> def a(x,y):
...   return list(set(x)-set(y))
...
>>> a(A,B)
[5]
>>> def b(x,y):
...   return filter(lambda A: A not in y, x)
...
>>> b(A,B)
[5]
>>> def c(x,y):
...   return [_ for _ in x if _ not in y]
...
>>> c(A,B)
[5]

【讨论】:

  • 您的第一个技术(正确)使用集合差异,而不是集合交集。
  • 抱歉,一边看电视一边回答堆栈溢出问题。谢谢提醒,我会改正的。
猜你喜欢
  • 2020-10-13
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
相关资源
最近更新 更多