Features of Python's set

The internal structure of set is very similar to that of dict, the only difference is that it does not store value, so it is very fast to judge whether an element is in the set.

The elements stored in a set are similar to the keys of a dict, and must be immutable objects. Therefore, any mutable objects cannot be placed in a set.

Finally, the elements stored in a set are also out of order.

Where can these features of set be applied?

Monday to Sunday can be represented by the strings 'MON', 'TUE', ... 'SUN'.

Suppose we let the user input a day from Monday to Sunday, how to judge whether the user's input is a valid week?

This can be determined with an if statement, but this is very tedious:

x = '???' # String entered by the user
if x!= 'MON' and x!= 'TUE' and x!= 'WED' ... and x!= 'SUN':
    print 'input error'
else:
    print 'input ok'

Note: The ... in the if statement indicates other week names that are not listed. Please enter them completely when testing.

If you create a set in advance, including 'MON' ~ 'SUN':

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

To judge whether the input is valid, you only need to judge whether the string is in the set:

x = '???' # String entered by the user
if x in weekdays:
    print 'input ok'
else:
    print 'input error'

This way, the code is much simpler.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325648078&siteId=291194637