简体   繁体   中英

Find in which of multiple sets a value belongs to

I have several sets of values, and need to check in which of some of them a given value is located, and return the name of that set.

value = 'a'
set_1 = {'a', 'b', 'c'}
set_2 = {'d', 'e', 'f'}
set_3 = {'g', 'h', 'i'}
set_4 = {'a', 'e', 'i'}

I'd like to check if value exists in sets 1-3, without including set_4 in the method, and return the set name. So something like:

find_set(value in set_1, set_2, set_3)

should return

set_1

Maybe some neat lambda function? I tried

w = next(n for n,v in filter(lambda t: isinstance(t[1],set), globals().items()) if value in v)

from Find if value exists in multiple lists but that approach checks ALL local/global sets. That won't work here, because the value can exist in several of them. I need to be able to specify in which sets to look.

Don't use an ugly hackish lambda which digs in globals so you can get a name; that will confuse anyone reading your code including yourself after a few weeks :-).

You want to be able to get a name for sets you have defined, well, this is why we have dictionaries. Make a dictionary out of your sets and then you can create handy/readable set/list comprehensions to get what you want in a compact readable fashion:

>>> d = {'set_1': set_1, 'set_2': set_2, 'set_3': set_3, 'set_4': set_4}

To catch all sets in which 'a' is located:

>>> {name for name, items in d.items() if 'a' in items}
{'set_1', 'set_4'}

To exclude some name add another the required clause to the if for filtering:

>>> {name for name, items in d.items() if 'a' in items and name != 'set_4'}
{'set_1'}

You can of course factor this into a function and be happy you'll be able to understand it if you bump into it in the future:

def find_sets(val, *excludes, d=d):
    return {n for n, i in d.items() if val in i and n not in excludes}

This behaves in a similar way as the previous. d=d is probably not the way you want to do it, you'll probably be better of using some **d syntax for this.


If you just want to get the first value, return the next(comprehension) from your function like this:

def find_sets(val, *excludes, d=d):
    return next((n for n, i in d.items() if val in i and n not in excludes), '')

The '' just indicates a default value to be returned if no elements are actually found, that is, when called with a value that isn't present, an empty string will be returned (subject to change according to your preferences):

>>> find_sets('1')
''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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