Append values to a set in Python

后端 未结 8 1966
一向
一向 2020-12-12 09:17

I have a set like this:

keep = set(generic_drugs_mapping[drug] for drug in drug_input)

How do I add values [0,1,2,3,4,5,6,7,8,9,10]

8条回答
  •  余生分开走
    2020-12-12 10:01

    The way I like to do this is to convert both the original set and the values I'd like to add into lists, add them, and then convert them back into a set, like this:

    setMenu = {"Eggs", "Bacon"}
    print(setMenu)
    > {'Bacon', 'Eggs'}
    setMenu = set(list(setMenu) + list({"Spam"}))
    print(setMenu)
    > {'Bacon', 'Spam', 'Eggs'}
    setAdditions = {"Lobster", "Sausage"}
    setMenu = set(list(setMenu) + list(setAdditions))
    print(setMenu)
    > {'Lobster', 'Spam', 'Eggs', 'Sausage', 'Bacon'}
    

    This way I can also easily add multiple sets using the same logic, which gets me an TypeError: unhashable type: 'set' if I try doing it with the .update() method.

提交回复
热议问题