Append values to a set in Python

后端 未结 8 1957
一向
一向 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:54

    Define set

    a = set()
    

    Use add to append single values

    a.add(1)
    a.add(2)
    

    Use update to add elements from tuples, sets, lists or frozen-sets

    a.update([3,4])
    
    >> print(a)
    {1, 2, 3, 4}
    

    If you want to add a tuple or frozen-set itself, use add

    a.add((5, 6))
    
    >> print(a)
    {1, 2, 3, 4, (5, 6)}
    

    Note: Since set elements must be hashable, and lists are considered mutable, you cannot add a list to a set. You also cannot add other sets to a set. You can however, add the elements from lists and sets as demonstrated with the ".update" method.

提交回复
热议问题