简体   繁体   中英

What's the best way to unpack a list of frozensets?

Not allowed to use any import.

Input:

[frozenset({1}), frozenset({32}), frozenset({40}), frozenset(), frozenset({76})]

Desired Output:

[1,32,40,76]

I'm looking for a concise way. I know how to unpack it with a muli-line for loop.

You can use a list comprehension to generate the output. In order to extract the value in each frozenset, you can create an iterator on it and use the next() method of the iterator to get the first and unique value, if it is not empty:

lst =  [frozenset({1}), frozenset({32}), frozenset({40}), frozenset(), frozenset({76})]

out = [next(iter(fset)) for fset in lst if fset]

print(out)
# [1, 32, 40, 76]

We can iterate in the list of frozenset, and change their datatype to list See here

l = [frozenset({1}), frozenset({32}), frozenset({40}), frozenset(), frozenset({76})]
arr = []
for element in l:
    new = list(element)
    if new != []:
        arr.append(new[0])
print(arr)

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