What is the feature of set, update, Traverse set, and set in Python

Source: Internet
Author: User

The role of Dict is to establish a set of keys and a set of value mappings, dict key cannot be duplicated.

sometimes, we just want to dict key, do not care about the value of key corresponding to the purpose is to ensure that the elements of this set will not be duplicated, then the set will come in Handy.

The set holds a series of elements, which are similar to the list, but the set elements are not duplicates and are unordered, which is similar to the Dict key.

The way to create a set is to call set () and pass in a list,list element as the set Element:

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

You can view the contents of the Set:

>>> print sset ([' A ', ' C ', ' B ')

Note that the above print form is similar to list, but it is not a list, and it can be seen that the order of printing and the order of the original list may be different because the elements stored inside the set are unordered .

Because set cannot contain duplicate elements, What happens when we pass in a list that contains repeating elements?

>>> s = set ([' a ', ' b ', ' C ', ' C ']) >>> print sset ([' a ', ' C ', ' B ']) >>> len (s) 3

The result shows that the set automatically removes the duplicate elements, the original list has 4 elements, but the set has only 3 Elements.

Task

Please use set to indicate 4 students in the Class:

Adam, Lisa, Bart, Paul.

Reference code:

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

Python's Access Set

Because set stores unordered collections , we cannot access them through an Index.

Accessing an element in a set actually determines whether an element is in the Set.

For example, a set that stores the name of a class student:

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

We can use the in operator to Judge:

Is Bart a classmate of the class?

>>> ' Bart ' in Strue

Is bill a classmate of the class?

>>> ' Bill ' in Sfalse

Is Bart a classmate of the class?

>>> ' Bart ' in Sfalse

It appears that the case is important, ' Bart ' and ' Bart ' are considered to be two different elements.

Task

Because the set above does not recognize lowercase names, improve set so that both ' Adam ' and ' Bart ' can return True.

Reference code:

s = set ([' Adam ', ' Bart '])
print ' Adam ' in S
print ' Bart ' in S

Features of Python's set

the internal structure of set is much like the dict, the only difference is that it does not store value, so it is very fast to determine whether an element is in Set.

the set stored element is similar to the Dict key, and must be an immutable object , so any mutable object cannot be placed in the Set.

finally, theset stores the elements that are not in order.

Where can these features of set be applied?

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

Suppose we let the user enter a day from Monday to Sunday, how to tell if the User's input is a valid week?

Can be judged with an if statement , but this is tedious:

# User Input string if x!= ' MON ' and x!= ' TUE ' and x!= ' WED ' ... and x!= ' SUN ':    print ' input error 'else:    print ' Input ok '  

note:in the IF statement ... Indicates that no other week names are listed, when testing, enter Complete.

If you create good one set beforehand, include ' MON ' ~ ' SUN ':

Weekdays = set ([' MON ', ' TUE ', ' WED ', ' THU ', ' FRI ', ' SAT ', ' SUN '])

To determine if the input is valid, just determine if the string is in Set:

# User Input string in  weekdays:    print ' input ok 'else:    print ' input error '  

In this way, the code is much simpler.

Task

The month can also be represented by a set, design a set and determine whether the month the user entered is VALID.

The month can be used with the string ' Jan ', ' Feb ', ... Said.

months = set ([' 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 '

Python's Traversal Set

Because set is also a collection, traversing set is similar to traversing a list and can be implemented through a for loop.

You can iterate through the elements of a set directly using a for loop:

In S:     ... Print name ... Lisaadambart

note: When observing a for loop, the order of the elements and the order of the list is likely to be different when traversing set, and the results of running on different machines may be different.

Task

Please use the For loop to traverse the set below to print out the name:score .

s = set ([' Adam ', ' + '), (' Lisa ', ' $ '), (' Bart ', 59)])
Reference code:
s = set ([' Adam ', ' + '), (' Lisa ', ' $ '), (' Bart ', 59)])
For x in s:
Print x[0]+ ': ', x[1]


Python's Update Set

Because set stores a set of unordered elements that are not duplicated , the update set mainly does two things:

One is to add the new element to the set, and the other is to remove the existing element from the Set.

When adding an element, use the Add () method of Set:

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

If the added element already exists in set, add () will not error, but will not be added:

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

When removing elements from a set, use the Remove () method of Set:

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

If the deleted element does not exist in the set, remove () will error:

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

So with add () can be added directly, and remove () before you need to Judge.

Task

For the following set, given a list, for each element in the list, if it is in set, it is deleted, if it is not in the set, it is Added.

s = set ([' Adam ', ' paul ']) L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
Reference code:
s = set ([' Adam ', ' Lisa ', ' Paul '])
L = [' Adam ', ' Lisa ', ' Bart ', ' Paul ']
For name in L:
If name in s:
S.remove (name)

S.add (name)
Print S

What is the feature of set, update, Traverse set, and set in Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.