简体   繁体   中英

Select an item from a set in Python

I am looking to select one item from a set. It does not matter which item it is, but I want it to be the same item every time the function is called.

For example, if I had the set:

my_set = set(["ABC","ABC inc", "ABC ltd"])

Then I want to return any one of those, but the same one whenever the function is run. [ie so I would always get "ABC", or always get "ABC inc" whenever I ran with the above set.] If I was using lists, I would just take the first item, but sets don't have a first per se.

This is in contrast to selecting randomly [eg How do I pick 2 random items from a Python set? ] where it will change every time it is run.

What about converting to list and sorting?

my_list = list(my_set)
my_list.sort()
chosen_element = my_list[0]

you could use a function with memoization

def get_random(my_set,memo={}):
    if id(my_set) not in memo:
       memo[id(my_set)] = random.choice(list(my_set))
    return memo[id(my_set)]

a_set = set([1,2,3,4,5])
print get_random(a_set)
print get_random(a_set)

this would always give you the same value as long as you passed in a_set ... (a different set would give a different answer)

if you wanted to make sure the item was still in the set you could change the memo if check

def get_random(my_set,memo={}):
    if id(my_set) not in memo or memo[id(my_set)] not in my_set:
       memo[id(my_set)] = random.choice(list(my_set))
    return memo[id(my_set)]

I may have misunderstood your question, but a check for membership in the set should work, if you are looking for anything specific.

letter_set = set(['abc','ABC','xyz','XYZ'])
check_string = 'ABC'
if check_string in letter_set:
    output = check_string

This should only give an output value if the desired string is in the set.

Use min() .

>>> my_set = set(["ABC","ABC inc", "ABC ltd"])
>>> min(my_set)
'ABC'

Raises ValueError if empty. From Python 3.4 a default value can be returned instead.

我为此找到的另一个答案是使用 min:

elem = min(mySet)

Maybe this can help you:

from iteration_utilities import first
from simple_benchmark import benchmark

def forLoop(s):
    value = len(s)/2
    found = None
    for elem in s:
        if elem == value:
            found = elem
            break
    return found


def getAndSet(s: set):
    value = len(s)/2
    s.remove(value)
    s.add(value)


argumente = {2 ** i: set(range(2 ** i)) for i in range(10, 13)}
a = benchmark([forLoop, getAndSet],
              argumente,
              argument_name='set element',
              function_aliases={first: 'First'})

print(a)

Output:

 forLoop getAndSet 1024 0.000023 4.393867e-07 2048 0.000046 5.612440e-07 4096 0.000091 5.677611e-07

Sets are implemented as hash tables. So the order is deterministic unless you insert/remove an element.

say x = set (['1','123','2','10'])

this set will always have an order '1', '2', '123', '10' (lexicographic I guess)

but if you are inserting or removing an element then you will have to use some sort of sorting function to make the order deterministic

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