比较列表数据的最有效方法

时间:2017-01-25 00:37:01

标签: python arrays list set compare

我正在使用python并尝试比较列表之间的数据。列表A=['perspectiveA', 'perspectiveB', 'perspectiveC']将包含如下数据:

B

列表B=['listB.data.perspectiveA', 'listB.data.perspectiveB', 'listB.data.perspectiveC']将包含如下数据:

A

我正在尝试确保列表B中收集的数据包含在列表A中收集的数据中。使用嵌套for循环是唯一的方法吗?我不想简单地看一下来自B的{​​{1}}中的项目是否属于while(getline(data, word, '\n')){ ss<<word; while(getline(ss, word, ',')){//prints entire file cout<<word<<endl; } } 中的一项,但我需要确保1:1的相关性。例如,列表B需要包含一个包含'perspectiveA'的项目,但只包含一个项目。

2 个答案:

答案 0 :(得分:0)

将两个列表转换为集合:

set('listB.data.' + x for x in A) == set(B)
# True

答案 1 :(得分:0)

为什么不将一个列表中的元素(列表A,因为它听起来像该列表中的数据是唯一的)移动到字典中,因为搜索该数据类型要快得多,并且您可以在那里保留您的计数器以及:

listA = ['perspectiveA', 'perspectiveB', 'perspectiveC']
listB = ['listB.data.perspectiveA', 'listB.data.perspectiveB', 'listB.data.perspectiveC']
dictA = {a:0 for a in listA}

>>> dictA
{'perspectiveA': 0, 'perspectiveB': 0, 'perspectiveC': 0}

for b in listB:
    value = b.split(".")[2]
    if value in dictA:
        dictA[value] += 1

任何值不是1的字典元素都不显示或重复。