Append values to a set in Python

后端 未结 8 1952
一向
一向 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 09:57

    This question is the first one that shows up on Google when one looks up "Python how to add elements to set", so it's worth noting explicitly that, if you want to add a whole string to a set, it should be added with .add(), not .update().

    Say you have a string foo_str whose contents are 'this is a sentence', and you have some set bar_set equal to set().

    If you do bar_set.update(foo_str), the contents of your set will be {'t', 'a', ' ', 'e', 's', 'n', 'h', 'c', 'i'}.

    If you do bar_set.add(foo_str), the contents of your set will be {'this is a sentence'}.

提交回复
热议问题