Python basics 2: python Basics

Source: Internet
Author: User

Python basics 2: python Basics

Set

Feature: A collection object is a group of unordered hash values. A set Member can be used as a dictionary key. Unlike the list and metadata, a set cannot be indexed by digits. In addition, the elements in the set cannot be repeated.

1 Define 2 3 set ()-> new empty set object4 set (iterable)-> new set object5 s = {0}

Application: deduplication

1 >>> lst1 = [1,1,2,2,3,4,2]2 >>> list(set(lst1))3 [1, 2, 3, 4]

Common Operations

For details, see the following code example:

1 >>> lst1 = [1, 2] 2 >>> lst2 = [2, 3] 3 >>> a = set (lst1) # define a set 4 >>> B = set (lst2) 5 >>> a, B 6 ({1, 2 },{ 2, 3 }) 7 >>> a | B # obtain the Union 8 {1, 2, 3} 9 >>> a & B # obtain the intersection 10 {2} 11 >>>> a-B # retrieve the difference set 12 {1} 13 >>> B-a # obtain difference set 14 {3} 15 >>> list () # convert a set to a list or convert it to a tuples. For example, tuple (a) returns () 16 [1, 2] 17 >>> a <B # subset judgment 18 False19 >>> c = set ([1]) 20 >>> c21 {1} 22 >>> c <a # subset judgment 23 True24 >>> c <= a # subset judgment 25 True26 >>> d = set ([ 1, 2, 3]) 27 >>> d> a # superset judgment 28 True29 >>> 30 >>> d >=a # superset judgment 31 True32 >>>, b33 ({1, 2 },{ 2, 3}) 34 >>> a ^ B # symmetric difference set 35 {1, 3} 36 >>> c37 {1} 38 >>> d39 {1, 2, 3} 40 >>> a ^ d # symmetric difference set 41 {3} 42 >>>> s = {0} 43 >>> type (s) 44 <class 'set'> 45 >>> 46 >>> print (s, len (s) # set length 47 {0} 148 >>>> s. add ('1') # add element 49 >>> s50 {0, '1'} 51 >>> s. update ([2, 3]) # add multiple elements 52 >>> s53 {0, 2, 3, '1'} 54 >>> s. remove (2) # delete a specified element. If no element exists, the following error occurs: 55 >>>> s56 {0, 3, '1'} 57 >>> s. pop () # delete any element (it seems useless) 58 059 >>>> s60 {3, '1'} 61 >>> s. discard (3) # delete a specified Element 62 >>> s63 {'1'} 64 >>> s. clear () # clear a set 65 >>> s66 set ()View Code

 

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.