set meaning and usage in the python

·

set in the python What does it mean?

set is a set of numbers, the disorder, the content can not be repeated, created by calling the set ():

1
>>> s = set([ 'A' , 'B' , 'C' ])

For the meaning of a set of access that would only see if an element in this collection there, observing case sensitive:

1
>>> print 'A' in sTrue>>> print 'D' in sFalse

Also to traverse through for:

1
s = set([( 'Adam' , 95), ( 'Lisa' , 85), ( 'Bart' , 59)]) for x in s:  print x[0], ':' ,x[1]>>>Lisa : 85Adam : 95Bart : 59

When added by add and remove, delete elements (holding not repeated), an additive element, with the SET add () method

1
>>> s = set([1, 2, 3])>>> s.add(4)>>> print sset([1, 2, 3, 4])

If the element to add already exists in this set, add () does not complain, but not added to the list:

1
>>> s = set([1, 2, 3])>>> s.add(3)>>> print sset([1, 2, 3])

When you delete elements in this set, remove set with the () method:

1
>>> s = set([1, 2, 3, 4])>>> s.remove(4)>>> print sset([1, 2, 3])

set in, remove () If you remove the element does not exist will get an error:

1
>>> s = set([1, 2, 3])>>> s.remove(4)Traceback (most recent call last): File "<stdin>" , line 1, in <module>KeyError: 4

So if we want to determine whether an element in a number of different conditions in line with the set is the best choice, the following example:

1
months = set([ 'Jan' , 'Feb' , 'Mar' , 'Apr' , 'May' , 'Jun' , 'Jul' , 'Aug' , 'Sep' , 'Oct' , 'Nov' , 'Dec' ,])x1 = 'Feb' x2 = 'Sun' if x1 in months:  print 'x1: ok' else print 'x1: error' if x2 in months:  print 'x2: ok' else print 'x2: error' >>>x1: okx2: error

Furthermore, computational efficiency is higher than the set list.

Guess you like

Origin www.cnblogs.com/hongawang/p/11079930.html