【问题标题】:TypeError: unsupported operand type(s) for &: 'list' and 'list' pythonTypeError:&:'list'和'list'python不支持的操作数类型
【发布时间】:2026-01-12 20:45:01
【问题描述】:

我在编写 Python 代码时遇到了这个非常奇怪的错误。这是一个与不受支持的操作数类型有关的 TypeError。我得到的错误如下:

names_in_both = jsonDataprevFile.keys() & jsonDatacurrFile.keys()
TypeError: unsupported operand type(s) for &: 'list' and 'list'

【问题讨论】:

  • 你想达到什么目的?
  • 您是否要使这两个列表相交?或者将它们连接起来?

标签: python json list python-2.7 dictionary


【解决方案1】:

我猜你正在尝试在字典中找到常用键。 Unfortunately, dict.keys returns a list, not a set,不支持交集运算符。只需将输出转换为set

names_in_both = set(jsonDataprevFile.keys()) & set(jsonDatacurrFile.keys())

更新:根据 python 3,dict.keys() 返回一个 dict_keys 对象,它允许执行 d1.keys() & d2.keys()

【讨论】:

    【解决方案2】:

    我猜你想要这个

    names_in_both = jsonDataprevFile.keys() + jsonDatacurrFile.keys()
    

    【讨论】:

      【解决方案3】:

      可以获得两个列表的共同元素

      list1 = jsonDataprevFile.keys()
      list2 = jsonDatacurrFile.keys()
      names_in_both = list(set(list1).intersection(list2))
      

      【讨论】:

        最近更新 更多