gpt4 book ai didi

python - 从 python 上的 dict 获取集合运算符

转载 作者:行者123 更新时间:2023-12-01 09:02:34 26 4
gpt4 key购买 nike

如果我有两个或更多集合,以及一个描述它们之间必须完成的操作的字符串,例如“and”,“or”,“xor”,显然可以这样完成:

if string == 'and': 
return set1.intersection(set2)
elif string == 'or'
return set1 | set2

等等。如果我想用字典来做怎么办?我有这样的东西:

dictionary = {'and': set.intersection, 'or': set.union}
return set1.dictionary[string](set2)

也尝试过

operation = dictionary.get(string)
return set1.operation(set2)

但是没有一个起作用。我如何才能获得与通过 ifs 但使用字典得到的相同结果?

最佳答案

您可以使用set.itersection()set.union()等作为静态方法,向它们传递多个集合:

>>> ops = {'and': set.intersection, 'or': set.union}
>>> set1 = {1, 2, 3}
>>> set2 = {3, 4, 5}
>>> ops['and'](set1, set2)
{3}
>>> ops['or'](set1, set2)
{1, 2, 3, 4, 5}

或者,您可以将操作映射到方法名称并使用 getattr() :

>>> ops = {'and': 'intersection', 'or': 'union'}
>>> getattr(set1, ops['and'])(set2)
{3}
>>> getattr(set1, ops['or'])(set2)
{1, 2, 3, 4, 5}

关于python - 从 python 上的 dict 获取集合运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52358002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com