Append values to a set in Python

2019-03-07 15:02发布

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] into this set?

6条回答
叛逆
2楼-- · 2019-03-07 15:22

Define set

a = set()

Use add to append single values

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

Use update to append iterable values

a.update([3,4])

Check your collection

a
Out[*n*]: {1, 2, 3, 4}

That's it - remember, update if it is iterable (aka list or tuple) or add if not. Happy coding!

查看更多
干净又极端
3楼-- · 2019-03-07 15:28

Use update like this:

keep.update(newvalues)
查看更多
疯言疯语
4楼-- · 2019-03-07 15:31

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'}.

查看更多
smile是对你的礼貌
5楼-- · 2019-03-07 15:32

For me, in Python 3, it's working simply in this way:

keep = keep.union((0,1,2,3,4,5,6,7,8,9,10))

I don't know if it may be correct...

查看更多
一夜七次
6楼-- · 2019-03-07 15:36
keep.update(yoursequenceofvalues)

e.g, keep.update(xrange(11)) for your specific example. Or, if you have to produce the values in a loop for some other reason,

for ...whatever...:
  onemorevalue = ...whatever...
  keep.add(onemorevalue)

But, of course, doing it in bulk with a single .update call is faster and handier, when otherwise feasible.

查看更多
劳资没心,怎么记你
7楼-- · 2019-03-07 15:45

You can also use the | operator to concatenate two sets (union in set theory):

>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}

Or a shorter form using |=:

>>> my_set = {1}
>>> my_set |= {2}
>>> my_set
{1, 2}

Note: In versions prior to Python 2.7, use set([...]) instead of {...}.

查看更多
登录 后发表回答