[英]How do I check if all elements fall in one group?
I have different product groups, let's say toys, clothes and food.我有不同的产品组,比如说玩具、衣服和食物。 When I get a series (or list) of products I want to know if they all fall in one group or if I have products from a few groups.
当我得到一系列(或列表)产品时,我想知道它们是否都属于一个组,或者我是否有几个组的产品。
Let's make an example:让我们举个例子:
toys=['Car', 'Teddy Bear', 'Doll']
food=['Banana', 'Cola', 'Bread', 'Milk']
So when I get ['Cola', 'Milk']
I want it to return True (they all fall in food) and when I get ['Milk', 'Banana', 'Car']
I want it to return False (contains products of both toys
AND food
).所以当我得到
['Cola', 'Milk']
我希望它返回 True (它们都掉进食物中)而当我得到['Milk', 'Banana', 'Car']
我希望它返回 False (包含toys
和food
的产品)。
Is there a way to check this other than looping trough all my groups and checking one by one if all products are in that specific group?除了循环遍历我的所有组并逐个检查所有产品是否都在该特定组中之外,还有其他方法可以检查吗?
Thank you!谢谢!
This is essentially a set operation.这本质上是一个集合操作。 You can convert the
toys
and food
to sets and then use set.intersection
.您可以将
toys
和food
转换为套装,然后使用set.intersection
。 For example:例如:
toys = ["Car", "Teddy Bear", "Doll"]
food = ["Banana", "Cola", "Bread", "Milk"]
toys, food = set(toys), set(food)
def is_only_one_group(l):
return bool(toys.intersection(l)) + bool(food.intersection(l)) == 1
print(is_only_one_group(["Milk", "Banana", "Car"]))
print(is_only_one_group(["Cola", "Milk"]))
Prints:印刷:
False
True
You can build dictionaries out of your lists such that entries of the lists are the keys and values are the name of the list they belong to.您可以从列表中构建字典,以便列表条目是键,值是它们所属列表的名称。 Then we can map the items in the new list and check if the number of unique elements is 1 or not:
然后我们可以 map 新列表中的项目并检查唯一元素的数量是否为 1:
toys_dict = dict.fromkeys(toys, "toys")
food_dict = dict.fromkeys(food, "food")
combined_dict = {**toys_dict, **food_dict}
def is_only_one_group(new_list):
return len(set(combined_dict[val] for val in new_list)) == 1
using as用作
>>> is_only_one_group(["Cola", "Milk"])
True
>>> is_only_one_group(["Milk", "Banana", "Car"])
False
You could use the set data structure in Python.您可以使用 Python 中的设置数据结构。
toys=['Car', 'Teddy Bear', 'Doll']
food=['Banana', 'Cola', 'Bread', 'Milk']
def is_in_one_group(my_list):
belongs_in_group = [set(my_list).issubset(toys), set(my_list).issubset(food)]
return sum(belongs_in_group) == 1
is_in_one_group(['Cola', 'Milk'])
# True
is_in_one_group(['Milk', 'Banana', 'Car'])
# False
is_in_one_group([])
# False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.