Getting Started with Python [] 6-2 set | defined set of access set, set of characteristics, traversing the set, update set

1, set definition

dict role is to establish a mapping between a set of key and a set value, dict the key can not be duplicated.

Sometimes, we just want dict key, and do not care key corresponding to the value, purpose is to ensure that the elements of the collection will not be repeated, this time, set comes in handy.

set to hold a series of elements, and a list like this, ** but the set of elements is not repeated, and is disordered, ** and this is the key dict like.

Create a set way:
call set () and passing in a list, list of elements as a set of elements:

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

You can view the contents of the set:

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

Please note that the print form similar list, but it is not a list, look carefully can find, order and print the original list of order might be different, because the set of internal storage elements are unordered.

Because the set can not contain duplicate elements, so when we pass list contains duplicate elements of what will happen?

>>> s = set(['A', 'B', 'C', 'C'])
>>> print s
set(['A', 'C', 'B'])
>>> len(s)
3

The results show, automatically remove duplicate set of elements, the list of the original four elements, but only three elements set.

Task:
Please indicate the class of four students with a set:

Adam, Lisa, Bart, Paul

Code:

s = set(['Adam','Lisa','Bart','Paul'])


2, set access

Because it is a collection of unordered set of storage, so we can not be accessed by index.

Access an element in the set is actually determine whether an element in the set.

For example, store a set of names of classmates:

>>> s = set(['Adam', 'Lisa', 'Bart', 'Paul'])

We can use the operator in determining:

Bart is the class of students do?

>>> 'Bart' in s
True

Bill is the class of students do?

>>> 'Bill' in s
False

bart is the class of students do?

>>> 'bart' in s
False

It seems case is important, 'Bart' and 'bart' is considered to be two different elements.

Task:
Due to the above set does not recognize the lowercase name, please set to improve, make 'adam' and 'bart' can return True.

Code:

s = set(['Adam', 'Lisa', 'bart', 'Paul'])
print 'adam' in s
print 'bart' in s


3, set features

Dict internal structure and the like set, the only difference is not stored value, thus determining whether an element in the set quickly.

Similar elements of the set and stored dict key, the object must be constant, and therefore, any variable object is not placed in set.

Finally, set the storage element is no order.

set of these features can be used in what place?

Monday to Sunday can use the string 'MON', 'TUE', ... 'SUN' representation.

Suppose we allow the user to enter a day from Monday to Sunday, how to determine whether the user's input is a valid weeks away?

It can be used to determine if statement, but this is very tedious:

x = '???' # 用户输入的字符串
if x!= 'MON' and x!= 'TUE' and x!= 'WED' ... and x!= 'SUN':
    print 'input error'
else:
    print 'input ok'

Note: if statement ... represents the other days of the week is not listed, test, enter the full.

If you previously created a good set, includes 'MON' ~ 'SUN':

weekdays = set ([ 'MON' , 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'])
and then determines if the input is valid, only needs to determine whether the string in the set :

x = '???' # 用户输入的字符串
if x in weekdays:
    print 'input ok'
else:
    print 'input error'

As a result, the code is much simpler.

Task:
month can also use the set represent, please design a set month and determine user input is valid.

The month may be the string 'Jan', 'Feb', ... represented.

Code:

months = set(['Jan','Feb'])
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'

Here Insert Picture Description





4, set traversal

Since the set is a set, so that traversal list set and traverse the like, can be achieved by a for loop.

It can be used directly for loop through the elements of the set:

>>> s = set(['Adam', 'Lisa', 'Bart'])
>>> for name in s:
...     print name
... 
Lisa
Adam
Bart

Note: observed for loop is traversed SET, and the order of the list elements is likely to be different, and the result of running on different machines may be different.

Task:
Please use for looping through the following set, print out the name: score come.

s = set([(‘Adam’, 95), (‘Lisa’, 85), (‘Bart’, 59)])

Code:

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

Since a set in which each element is a tuple type data elements can be accessed using the access method for each tuple set and read elements inside

Here Insert Picture Description



5, update set

Since the set is stored in a set of non-repetition of disorderly elements, therefore, updated set mainly do two things:

First, add a new element to the set, the second is to delete existing elements from this set.

When the additive elements, with the set of add () method:

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

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

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

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

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

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

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

Therefore, the use add () may be added directly, and remove () requires prior determination.

Task:
For the following set, given a list, to list each element, if in the set, will be deleted, if not set in, it added.

s = set([‘Adam’, ‘Lisa’, ‘Paul’])
L = [‘Adam’, ‘Lisa’, ‘Bart’, ‘Paul’]

Code:

s = set(['Adam', 'Lisa', 'Paul'])
L = ['Adam', 'Lisa', 'Bart', 'Paul']
for name in L:
    if name in s:
        s.remove(name)
    else:
        s.add(name)
print s

Reference Code:

s = set(['Adam', 'Lisa', 'Paul'])
L = ['Adam', 'Lisa', 'Bart', 'Paul']
m = set(L)
p = s -m
q = m -s
s = p | q
print s
Published 20 original articles · won praise 0 · Views 411

Guess you like

Origin blog.csdn.net/yipyuenkay/article/details/103962368
set
set