【问题标题】:Compare all lists in a dictonary to each other比较字典中的所有列表
【发布时间】:2018-10-17 13:21:16
【问题描述】:

在python中是否可以比较以下结构中的所有对象

我有一个列表字典,每个列表中都有对象,例如

[
      [object1,object2,object3],
      [object4,object5,object6],
      [object7,object8,object9],
]

我想通过每个列表中的属性将所有对象相互比较,并确定哪些对象不在每个列表中。

根据反馈,请参阅下面的示例

from collections import defaultdict
from pprint import pprint

class mytest:
  def __init__(self, no, description):
    self.no = no
    self.description = description

data = []


x = mytest(1,'test1')
x2 = mytest(2,'test1')

x3 = mytest(1,'test2')
x4 = mytest(2,'test2')
x5 = mytest(3,'test2')


x6 = mytest(1,'test3')
x7 = mytest(2,'test3')
x8 = mytest(4,'test3')


data.append(x)
data.append(x2)
data.append(x3)
data.append(x4)
data.append(x5)
data.append(x6)
data.append(x7)
data.append(x8)


groups = defaultdict(list)

for obj in data:
    groups[obj.description].append(obj)

new_list = groups.values()


#i want to find out what items are not in each list
for list in new_list:
    pprint(list)


#example x8 = mytest(4,'test3') is only in one of the list so is missing from list 1 and 2

希望这会有所帮助

【问题讨论】:

  • 这似乎是一个列表列表,而不是列表字典。
  • @jpp 我添加了一个例子希望这会有所帮助
  • @AndrewMcDowell 你是对的,它是一个列表列表
  • 您想知道每个列表中缺少哪些对象,或者缺少哪些数字 (self.no)?
  • @AndrewMcDowell 每个列表中缺少哪些数字(self.no),尽管对象的工作方式过于理想,但我只需要列表之间缺少的列表,谢谢

标签: python python-object


【解决方案1】:

我认为这就是您要寻找的。我们创建一组obj.no 的可能值,然后使用集合差分运算符(在两个集合上使用-,以获取缺失的元素)。

# Get a set of all the no. values present in the data.
combined_set_of_values = set([item.no for item in data])

# Get the sets of obj.no values grouped by description.
for obj in data:
    groups[obj.description].append(obj.no)

new_list = groups.values()


# Print the list, and the elements missing from that list
for list in new_list:
    print("Values in list:")
    print(list)
    # Use set difference to see what's missing from list.
    print("Missing from list:")
    print(combined_set_of_values - set(list))

这给出了以下输出:

Values in list:
[1, 2]
Missing from list:
{3, 4}
Values in list:
[1, 2, 3]
Missing from list:
{4}
Values in list:
[1, 2, 4]
Missing from list:
{3}

【讨论】:

  • 非常感谢我正在寻找的东西 :)
  • 没问题。感谢您编辑您的问题以使其更清晰!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-21
  • 1970-01-01
  • 2017-12-20
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
相关资源
最近更新 更多