简体   繁体   English

如何将列表中的元素与另一个元素是字典的列表中的元素进行比较?

[英]How compare elements in a list with elements in another list whose elements are dicts?

I have a list of strings, for example:我有一个字符串列表,例如:

list1 = ['apple', 'orange', 'pear', 'peach']

and another list whose elements are dictionaries, like so:和另一个元素是字典的列表,如下所示:

list2 = [{'fruit': 'pear', 'size': 'big', 'rating': 7}, {'fruit': 'apple', 'size': 'small', 'rating': 6},{'fruit': 'peach', 'size': 'medium', 'rating': 7}, {'fruit': 'banana', 'size': 'big', 'rating': 9}]

For each element in list1, I need to determine if it appears as a value for any of the 'fruit' keys in list2's dictionaries.对于 list1 中的每个元素,我需要确定它是否显示为 list2 字典中任何“水果”键的值。 In this case, apple, pear and peach are all values of at least one 'fruit' key in list2, while orange is not.在这种情况下,apple、pear 和 peach 都是 list2 中至少一个“fruit”键的值,而 orange 则不是。 For each element in list1, how can I get a boolean true/false of whether it appears as a value for any 'fruit' key in list2?对于 list1 中的每个元素,如何获得布尔值真/假,以判断它是否显示为 list2 中任何“水果”键的值?

You do some kind of for or list comprehension checking if the value is present in any of the elements of the second list , for example:如果该值存在于第二个list any元素中,您可以进行某种forlist comprehension检查,例如:

list1 = ['apple', 'orange', 'pear', 'peach']
list2 = [{'fruit': 'pear', 'size': 'big', 'rating': 7}, {'fruit': 'apple', 'size': 'small', 'rating': 6},{'fruit': 'peach', 'size': 'medium', 'rating': 7}, {'fruit': 'banana', 'size': 'big', 'rating': 9}]

booleans = [
    any(fruit == f_dict['fruit'] for f_dict in list2) for fruit in list1
]

print(booleans)
>>> [True, False, True, True]

This will create a dictionary for every value in list one where the value is a boolean which is true if the value is in list2's values这将为列表一中的每个值创建一个字典,其中该值是一个布尔值,如果该值在 list2 的值中则为 true

def ItemInList(name, list):
    for dic in list:
        for item in dic.values():
            if name == item:
                return True
    return False



list1 = ['apple', 'orange', 'pear', 'peach']
list2 = [{'fruit': 'pear', 'size': 'big', 'rating': 7}, {'fruit': 'apple', 'size': 'small', 'rating': 6},{'fruit': 'peach', 'size': 'medium', 'rating': 7}, {'fruit': 'banana', 'size': 'big', 'rating': 9}]
dict = {}

for item in list1:
    dict[item] = ItemInList(item, list2)

print(dict)
[ x in [y['fruit'] for y in list2] for x in list1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM