以列表为元素的Python字典及其比较

时间:2019-02-11 02:46:17

标签: python

如果我的字典中有这样的列表:

dic = {"j" : ["a", "b", "c", "d", "e", "f", "g"], "a" : [ "h", "b", "f"], "c": ["g", "i"]}

如何制作一个代码,该代码首先检查是否有任何字典键以字符串形式存在于值列表中。如果他们确实比较了这两个键的值并计算了相似度。

例如,该词典的最终结果将是:

{'a': 0, 'c': 0, 'j': 3}

4 个答案:

答案 0 :(得分:1)

以下代码针对renderFrmHoras中的每个render() { return ( ... </View> <View> {this.renderFrmHoras()} </View> <DateTimePicker ... /> ... ); } 报告顶级字典键中任何相关项出现了多少次:

key

答案 1 :(得分:0)

目前还不清楚,但是我可以回答。

因此,要获取每个键的值以查看它们是否为键,请执行以下操作:

>>> [i for i in d if any(x in d for x in d[i])]
['Family']
>>> 

要获取所有值的计数:

>>> from collections import Counter
>>> Counter([x for i in list(d.values()) for x in i])
Counter({'Dog': 2, 'Mom': 1, 'Dad': 1, 'Sister': 1, 'Grandmother': 1, 'House': 1, 'Cat': 1, 'Hamster': 1, 'Kitchen': 1})
>>> 

要变得最普通:

>>> Counter([x for i in list(d.values()) for x in i]).most_common()[0][0]
'Dog'
>>> 

最终答案:

使用以下内容:

>>> {k:int(any(i in d for i in v)) for k,v in d.items()}
{'Family': 1, 'House': 0}
>>> 

答案 2 :(得分:0)

from collections import Counter


def search(d, key):
    def number_of_matches_in_lists(l1, l2):
        c1 = Counter(l1)  # see https://docs.python.org/3/library/collections.html#collections.Counter
        c2 = Counter(l2)
        return sum((c1 & c2).values())  # get total cout of all matching elements

    matches = 0
    list1 = d[key]
    for key2 in list1:  # iterate over items in the list
        if key2 in d:
            list2 = d[key2]
            # add number of matching items in list1 and list2 to total
            matches += number_of_matches_in_lists(list1, list2)

    return matches


if __name__ == '__main__':
    d = {"Family": [
        "Mom", "Dad", "Dog", "Sister",
        "Grandmother", "House"],
        "House": [
            "Dog", "Cat", "Hamster", "Kitchen"]
    }
    print(search(d, "Family"))
    print(search(d, "House"))

答案 3 :(得分:0)

您可以尝试

a = {"Family": [
     "Mom", "Dad", "Dog", "Sister",
     "Grandmother", "House"],
 "House": [
     "Dog", "Cat", "Hamster", "Kitchen"]
}

all_keys = a.keys()

result = {}

for key,val in a.iteritems():
    result[key] = 0
    for data in all_keys:
        if data in val:
            result[key] = result[key]+1

print result

您将获得输出

{'House': 0, 'Family': 1}