Python Learning Diary---Collection

Source: Internet
Author: User

I. How to construct a collection:

Set name = Set ()

1. Set () can have a parameter, the parameter type must be iterative, such as a string, a list, can be split into separate elements of the meaning

2. If the parameter is not taken, an empty set is constructed

>>> ASet = set ("ABCD") #参数为字符串 >>> aset{' C ', ' B ', ' d ', ' a '}>>> bSet = [' A ', 1.5, ' set '] #参数为普通 List >>> bset[' A ', 1.5, ' set ']>>> list = [1,1,2,2,3,3] #列表中有重复元素, building a collection with this list ignores duplicate elements >>> CSet =set (l IST) >>> Cset{1, 2, 3}>>> nullset = set () #构建空集 >>> Nullsetset ()


Two. Functions related to the collection

Len (): As with other collection types, determines the number of elements

In: Determines whether an element is in the collection, returns a Boolean value

For: Used to iterate over the elements in the collection


Three. Collection methods

The following methods are used in the same way as mathematical concepts:

Set A.intersection (set B) #判断AB集合交集

Set A.union (set B) #判断集合AB的并集

Set A.difference (set B) #判断集合A和集合B的差集

Set A.symmetric_difference (set B) #判断AB集合的对称差//ab intersection of Set-ab

Set A.issubset (set B) #判断A是否为B的子集

Set A.issuperset (set B) #判断A是否为B的超集


Other collection methods:

Set A.add (Element) #向集合A中添加元素element, no effect if present

Sets the A.clear () #删除集合A中的元素 to make it an empty set


Set A.remove (Element) #删除集合A中元素element, element does not exist will error

Set A.discard (Element) #删除集合A中元素element, element does not exist no error

Copy () #返回集合的浅拷贝

Python Learning Diary---Collection

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.