Python Basic data type

Source: Internet
Author: User
Tags extend

Python mutable and immutable objects

All of the data in Python is built around objects, which can be divided into two categories: mutable objects and immutable objects. When a variable is assigned a value, the variable holds an object reference (which can be understood as a pointer in C), pointing to the area in memory where the object resides.
For an immutable object, the object itself cannot be changed (or it can be understood that the value of an object cannot be changed), and a reference to that object can be changed.
For mutable objects, the contents of the object itself can be changed, and the reference to that object is constant ~

Immutable objects

Immutable objects are: Int,string,float,tuple ...
Once a immutable object is created, the object itself cannot be changed. If the value of the variable needs to be changed, only re-create the object and change the reference to the variable, as shown in:

The original object is no longer referenced and will be garbage collected ~ and can be verified using the ID () function as follows:

>>> abc = 1>>> id(abc)1456500192>>> abc=2>>> id(abc)1456500224
mutable objects

mutable objects are: list,dict ...
The contents of the Mutable object can be changed, and the reference to the variable is not changed, as shown in:

As you can see, for mutable objects, variable values do not need to be re-created, and mutable objects in Python are often container objects (that is, one object contains references to other objects)

>>> abc=[‘a‘,‘b‘]>>> id(abc)2768889238408>>> abc+=[‘c‘]>>> id(abc)2768889238408>>> abc[‘a‘, ‘b‘, ‘c‘]

In Python, it is possible to determine whether two variables are referenced from the same object, as in the example below:

>>> a = 1>>> b = 1>>> a is bTrue>>> c = 2>>> a is cFalse

Because there is a small integer object pool in Python, an integer object in the range [-5,257], the Python interpreter is not created repeatedly ~

Python Basic data type number

There are many types of numbers in Python, including: Integer, Long Integer, Boolean, floating point, plural. Once a number is defined, it cannot be changed (immutable objects)

--Integral type

The integer type in Python is in octal, decimal, and hexadecimal notation:

# 环境为 python3>>> 1                # 默认为十进制1>>> oct(8)        # 八进制,"0o" 为前缀,python2.7中的前缀为"0",10表示为‘010‘‘0o10‘>>> hex(10)      

Data type conversions, which can be converted to integers using int ():

>>> a = ‘12‘>>> b = int(a)       # 字符串类型转换为整型>>> b12>>> int(1.2)          # 浮点数转换为整型,小数部分会被略去1
--Long integer type

The integral type in the Python2 has a length limit, and the length of the 32-bit system is 32 bits, the value range is 64 bits on the -2**31~2**31-1;64 bit system, and the value range is -2**63~2**63-1.
There is no length limit for long integers in Python3, which can be infinitely large, but this is limited by the size of the memory (it is impossible to be infinitely large)

# 环境为 python2.7>>> a = 1              # 定义整型>>> a   1>>> b = 2L            # 定义长整型>>> b2L>>> a = 9999999999999999999999999999999999>>> a9999999999999999999999999999999999L

By adding uppercase L or lowercase l to a number to denote a long integer, and when defining an integral type, if the number of bits in the data exceeds the limit, it is converted to a long integer by default

Tip: in Python3, integer and long integers are categorized as: integer type int

--Boolean bool

True and False, or denoted by 1 and 0:1 means true,0 represents false~
When the condition is judged, if the conditional statement is returned as a non-0 value, a non-empty string, a non-empty list, and so on, it is represented as true, otherwise it is represented as false.

if []:    print(‘OK‘)else:    print(‘NO‘)结果输出:NOwhile 1:                 # 等效于while true,无限循环    print(‘hello world‘)
--Floating point float

Floating-point numbers in Python, which are decimals, can be represented in ordinary ways, such as:

1.23,3.56 ...

You can also use scientific notation to indicate:

1.23*10^9就是1.23e9,或者12.3e8         # 小数位数太多时,用科学计数法表示~0.000012可以写成1.2e-5

?

Integers and floating-point numbers are stored inside the computer in different ways, integer operations are accurate, and floating-point arithmetic may have
The rounding error.

--plural complex

The complex number consists of real and imaginary parts, the general form is X+yj, where x is the real part of the complex, and Y is the imaginary part of the complex, where x and y are real numbers. The letter J of the imaginary part can be written in all sizes.

&gt;&gt; a = 1.3 + 2.5j&gt;&gt; a(1.3+2.5j)&gt;&gt; type(a)<class ‘complex‘&gt;

The operation of numeric values is not introduced here.

String

The string is an ordered set of characters, and the string is an immutable object, once created, cannot be changed ~

--Create a string

Python strings can be created using single quotes or double quotes

str1 = ‘Hello‘str2 = "World"

Single or double quotation marks preceded by R, you can invalidate special characters in the string, output as-is:

>>> print(‘abc\tde‘)abc     de>>> print(r‘abc\tde‘)abc\tde

When R is used with a Unicode string, U needs to precede r

str1 = ur‘abc\tde
--Common string operations
var1 = ‘Hello‘; var2 = ‘Kitty‘# 字符串拼接var1 + var2       # 输出:‘HelloKitty‘# 重复输出var1 * 3            # 输出:‘HelloHelloHello‘# 成员运算,判断字符是否存在于指定字符串中‘t‘ in var2          # 输出:True,存在返回True‘a‘ not in var2   # 输出:True,不存在返回True# 原始字符串输出,字符串中的转移字符失效,在引号前使用 R 或 r 均可~print(r‘\t\n‘)     # 输出:\t\nprint(R‘\t\n‘)    # 输出:\t\n
--Three quotation marks (triple quotes) use

The three quotation marks in Python for cross-line output, for example to output the following statement:

line1---line2---line3---

Way One:

>>> str1 = "line1---\nline2---\nline3---">>> str1‘line1---\nline2---\nline3---‘>>> print(str1)line1---line2---line3---

Way two (3 pairs of single quotes or 3 pairs of double quotes, as a result) Pycharm environment:

str2 = ‘‘‘line1---line2---line3---‘‘‘print(str2)输出结果:line1---line2---line3---

3 pairs of double quotes "" "" "" or 3 pairs of single quotes "" can also represent multiple lines of comment (where # is the line comment):

class Abc():  """    多行注释    多行注释    多行注释    """  def __init__(self):      pass  def say_hello(self):      # 单行注释      # 单行注释      return ‘hello‘
--String common operations

---- String Index

>>> my_str = ‘hello‘>>> my_str[4]‘o‘>>> my_str[-3]        # 最后第3个字符‘l‘

---- intercept Strings

>>> my_str = ‘hello‘>>> my_str[1:4]        # 截取其中的 第2个到第5个 字符‘ell‘>>> my_str[:4]‘hell‘                          # 截取其中的 第1个到第4个 字符,不包括 my_str[4]>>> my_str[3:]‘lo‘                            # 截取其中的 第4个到最后1个字符>>> my_str[:-3]‘he‘                           # 截取第1个到最后第3个字符(不包括最后第3个)>>> my_str[-3:-1]‘ll‘                            # 截取倒数第3个到倒数第1个字符(不包括倒数第一个)>>> my_str[-3:]‘llo‘                           # 截取倒数第3个到最后一个字符>>> my_str[::-1]‘olleh‘                       # 生成一个与原字符串顺序相反的字符串

---- cutting, merging strings
To cut a string by a character in a string

>>> my_str = ‘a,b,c,d,e‘>>> my_str.split(‘,‘)[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]             # 返回列表

Merging elements in a list or tuple into strings

>>> ‘:‘.join([‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘])     # 列表‘a:b:c:d:e‘>>> ‘#‘.join((‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘))   元组‘a#b#c#d#e‘

---- Other Actions

>>> my_str = ‘ abc ‘>>> len(my_str)       # 获取字符串长度5# 移除字符串两边空白>>> my_str.strip()‘abc‘# 移除字符串左边空白>>> my_str.lstrip()‘abc ‘# 移除字符串右边空白>>> my_str.rstrip()‘ abc‘# 查找字符>>> my_str.index(‘b‘)    # 若字符串中没有该字符,会返回报错信息2# 查找字符串S.find(substr, [start, [end]])     # [start, [end]] 指定起始位置和结束位置>>> my_str.find(‘bc‘)2                                 # 返回查找到的字符串的第一个字符的索引,若没有找到,返回-1# 搜索和替换S.replace(oldstr, newstr, [count])   # count 指定替换次数>>> my_str.replace(‘b‘,‘B‘,2)‘aBc aBc abc‘>>> my_str = ‘abCD efg‘>>> my_str.lower()               # 都转为小写‘abcd efg‘>>> my_str.upper()              # 都转为大写‘ABCD EFG‘>>> my_str.swapcase()       # 大小写互换‘ABcd EFG‘>>> my_str.capitalize()        # 首字母大写‘Abcd efg‘

Use STR () to convert other types of data into strings

>>> str(123456)‘123456‘>>> str([‘a‘,‘b‘,‘c‘])"[‘a‘, ‘b‘, ‘c‘]"
List

Each side of the list uses [] contains, and [] can hold multiple types of data, separated by commas (,) between each data. List Data mutable objects ~

--Create a list
方式一:my_lst1 = [‘a‘, 1, 2]方式二:my_lst2 = list(‘abc‘)方式三:my_lst3 = list([‘a‘, 1, 2])

To create an empty list:

my_lst = []my_lst = list()
--List common operations
# index >>> my_lst = [' A ', ' B ', ' C ', ' d ']>>> my_lst[2] ' C ' # search list elements >>> my_lst.index (' C ') 2 # return index, if no corresponding element, return error message # list length >>> len (my_lst) 4# list of slices, using the same way as string, do not make sense comments >>> my_lst = [' A ', ' B ' , ' C ', ' d ']>>> my_lst[1:3][' B ', ' C ']>>> my_lst[:3][' A ', ' B ', ' C ']>>> my_lst[2:][' C ', ' d '] >>> my_lst[:-2][' A ', ' B ']>>> my_lst[-3:-1][' B ', ' C ']>>> my_lst[-3:][' B ', ' C ', ' d ']>> > my_lst[::-1][' d ', ' C ', ' B ', ' A ']# append Element (append append) >>> my_lst = [1,2,3]>>> my_lst.append (4) # [1, 2, 3, 4]# append element (extend append) >>> My_lst = [1,2,3]>>> my_lst.extend ([4,5]) # [1, 2, 3, 4, 5]# append with The difference between extend is that append appends objects directly, extend iterates over each element in the object, and then appends >>> my_lst = [1,2,3]>>> my_lst.append ([4, 5]) # [1, 2, 3, [4, 5]]>>> my_lst = [1,2,3]>>> my_lst.extend ([4, 5]) # [1, 2, 3, 4, 5]# inserts an element at the specified index location >&gt ;> My_lst = [1,2,3]>>> my_lst.insert ( -1, ' a ') # last element inserted in front of >>> my_lst[1, 2, ' a ', 3]>>> my_lst.insert (0, 0) # first element in front of insertion Into >>> my_lst[0, 1, 2, ' a ', 3]# delete element >>> a = My_lst.pop () # no parameter deletes the last element by default and removes the element return >>> my_lst[ 0, 1, 2, ' a ']>>> a3# pop () specify the parameters, by deleting >>> my_lst.pop (1) 1>>> my_lst[0, 2, ' a ']# delete the specified value in the list Li.rem  Ove (' AA ') >>> my_lst.remove (' a ') # If the element is not in the list, return an error message >>> my_lst[0, 2]# Delete the element by index and slice >>> my_lst = [' A ', ' B ', ' C ', ' d ']>>> del my_lst[0:2]>>> my_lst[' C ', ' d ']# clear list >>> my_lst.clear () >> > my_lst[]# list element occurrences >>> my_lst = [' A ', ' B ', ' C ', ' d ', ' a ']>>> my_lst.count (' a ') 2>>> My_lst . Count (' g ') 0# Flip list >>> my_lst = [' A ', ' B ', ' C ', ' d ']>>> my_lst.reverse () >>> my_lst[' d ', ' C ', ' B ', ' a ']

in operation----List (returns a Boolean value)
Determine if an element exists in the list ~

>>> my_lst = [‘a‘, ‘b‘, ‘c‘, ‘d‘]>>> print(‘a‘ in my_lst)True>>> print(‘z‘ in my_lst)False
-- Loop List

Only the For loop is described here

my_lst = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]for i in my_lst:    print(i)for i in range(len(my_lst)):    print(my_lst[i])

The output of the above two methods is consistent ~

You can use the enumerate function to output along with index, first understand the following enumerate:

my_lst = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]for i in enumerate(my_lst):    print(i)输出:(0, ‘a‘)(1, ‘b‘)(2, ‘c‘)(3, ‘d‘)(4, ‘e‘)# 所以可以这样使用:my_lst = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]for index, value in enumerate(my_lst):    print(‘%s --> %s‘ % (index, value))输出:0 --> a1 --> b2 --> c3 --> d4 --> e

Tip:enumerate The second parameter, can change the starting sequence number, you can try ~

Tuples and strings can be converted to lists through list (), which is one of the ways to initialize a list

lst_1 = list((1,2,3))     # [1, 2, 3]lst_2 = list(‘abc‘)        # [‘a‘, ‘b‘, ‘c‘]

Conversion from a dictionary

>>> my_dict = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}>>> list(my_dict)                  # 将字典中的 keys 转为 list[‘a‘, ‘b‘, ‘c‘]或者>>> list(my_dict.keys())[‘a‘, ‘b‘, ‘c‘]>>> list(my_dict.values())     # 将字典中的 values 转为list[1, 2, 3]
Meta-group

Tuples are similar to lists, with () containing their elements, and the biggest difference between tuples and lists is that tuples are immutable objects, and once created, their contents cannot be changed.

--Create a tuple
tup_1 = (‘a‘, ‘b‘, 1, 2)tup_2 = (1, 2, 3, 4)tup_3 = ‘a‘, ‘b‘, ‘c‘, ‘d‘

Create an empty tuple

tup_4 = ()

Create a tuple that contains only one element:

>>> tup_4 = (2)   # 这样创建 tup_4 会被当做 int 类型,而不是 tuple;>>> type(tup_4)<class ‘int‘># 正确创建方式>>> tup_4 = (2,)>>> type(tup_4)<class ‘tuple‘>
--common operations for tuples

The tuple's index operation (Tup[index]), the search element (Tup.index ()), the length (Len (tup)), The Slice (Tup (1:3)), the number of occurrences of the element (Tup.count ()), and so on, are consistent with the list ~

Operations such as Append,insert,extend,pop,remove,del,clear are not supported because the tuple is an immutable object

>>> tup_1 = (1,2,3)>>> tup_1[1] = 4Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: ‘tuple‘ object does not support item assignment

Tuple does not support sort and reverse operations, supports sorted operations, returns type as List

>>> tup_1 = (2,3,90,6,234,1,53,2)>>> sorted(tup_1)[1, 2, 2, 3, 6, 53, 90, 234]

A tuple also supports in operations:

>>> my_tup = (‘a‘,‘b‘,‘c‘,‘d‘)>>> print(‘a‘ in my_tup)True>>> print(‘z‘ in my_tup)False

The above-mentioned circular operation for list also applies to tuple~

A tuple () can be applied to a list, a string, and convert it to a tuple type of data

tup_1 = tuple("abcdefg")      # (‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘)tup_2 = tuple([1,2,3,4,5])     # (1, 2, 3, 4, 5)

Conversion from dictionary, similar to list

list(my_dict.keys())  或者 list(my_dict)    # 将字典中的 keys 转成tuplelist(my_dict.values())                              # 将字典中的 values 转成tuple              
Dictionary

Dictionaries also belong to mutable objects, using a pair of curly braces {} to contain elements, each element in the dictionary is a key->value pair, a colon is used between key and value: Split, separated by commas between each element ~

The key in tip:dict must be an immutable object, or a hash type (for example, a tuple can be a key), value can be a mutable object, or it can be an immutable object ~

--Create a dictionary
d1 = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}d2 = dict({‘a‘: 1, ‘b‘: 2, ‘c‘: 3})d3 = dict(a=1, b=2, c=3)    # 这种方式定义字典,key 只能是字符串类型d4 = dict([(‘a‘, 1), (‘b‘, 2), (‘c‘, 3)])# 初始化字典d6 = {}.fromkeys([‘a‘, ‘b‘], None)  # {‘a‘: None, ‘b‘: None}d7 = {}.fromkeys([‘a‘,‘b‘], [1, 2])   # {‘a‘: [1, 2], ‘b‘: [1, 2]}

To create an empty dictionary:

The cycle of the dictionary (d.keys,d.values, for I in D takes out the key)
Dict.get (Key)
Dict.setdefault ()

--Dictionary common operation
# Get dictionary elements >>> my_dict = {' A ': 1, ' B ': 2, ' C ': 3}>>> my_dict[' B ']2# is obtained using the Get method, if no key specified is returned as none>> > my_dict.get (' B ') when there is only one argument, the scope get of SetDefault is similar to finding the specified key if none is returned. When the specified key is not, it will not only return none, but will also add the key to the dictionary with a value of none>>> my_dict.setdefault (' C ') 3>>> My_dict.setdefault (' d ') >>> my_dict{' A ': 1, ' B ': 2, ' C ': 3, ' d ': none}# added key, can also be specified value>>> my_dict.setdefault (' E ', 5) 5> >> my_dict{' A ': 1, ' B ': 2, ' C ': 3, ' d ': None, ' e ': 5}# add operation >>> my_dict = {' A ': 1, ' B ': 2, ' C ': 3}&GT;&GT;&G T my_dict[' d '] = 4>>> my_dict{' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}# Modify Operation >>> my_dict[' d '] = 40>>> my_di Ct{' A ': 1, ' B ': 2, ' C ': 3, ' d ': 40}# delete operation >>> My_dict.pop (' a ') 1>>> my_dict{' B ': 2, ' C ': 3, ' d ': 40}# empty Dictionary >>> my_dict.clear () >>> my_dict{}# Update operation, updates the element in one dictionary (d_1) to another dictionary (d_2), d_1 if key,d_2 in D_ Key in the 1 update d_2, if not in the d_1 in Key,d_2, then add in the d_2, such as the following:>>> d_1 = {' A ': 1, ' B ': 2, 'C ': 3}>>> d_2 = {' A ':, ' X ': ten, ' y ': ' z ': 30}>>> d_1.update (d_2) >>> d_1{' A ':, ' B ': 2, ' C ': 3, ' X ': ten, ' y ': +, ' Z ': 30}
--cyclic operation of the dictionary

The dictionary's items () function returns a list of the traversed (key, value) tuples.

my_dict = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}for i in my_dict.items():    print(i)结果输出:(‘a‘, 1)(‘b‘, 2)(‘c‘, 3)

Keys (), VALUES ()

my_dict = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}for i in my_dict.keys():                    # keys() 获取字典的所有 key, 并以列表形式返回    print(i)结果输出:abcmy_dict = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}for i in my_dict.values():                 # values() 获取字典的所有 value, 并以列表形式返回    print(i)结果输出:123

In Python2, there are also items (), keys (), the values () function, which returns a list of copies of a dictionary (Items,keys or values), corresponding to Iteritems (), Iterkeys (), Itervalues ( ), which returns an iterator for all items (key,value) in the dictionary, which consumes extra memory and does not

In Python3, the Iteritems (), the Iterkeys (), the itervalues () function are discarded, the items (), keys (), values () are substituted, their results are returned with Python2 in Iteritems (), Iterkeys (), itervalues () consistent

You can also traverse a dictionary without using the above functions:

my_dict = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3}for key in my_dict:                          # 遍历字典中的所有key    print(my_dict[key])
Use of the--dict () conversion

List to Dictionary
Way One:

>>> ls_key = [‘a‘, ‘b‘, ‘c‘]>>> ls_value = [1, 2, 3]>>> dict(zip(ls_key, ls_value)){‘a‘: 1, ‘b‘: 2, ‘c‘: 3}

Way two:

>>> ls_key_value = [[‘a‘, 1], [‘b‘, 2], [‘c‘, 3]]>>> dict(ls_key_value){‘a‘: 1, ‘b‘: 2, ‘c‘: 3}

String to Dictionary
Way One:

import jsonuser_str = ‘{"name" : "Kitty", "gender" : "female", "age": 18}‘# user_str = "{‘name‘ : ‘Kitty‘, ‘gender‘ : ‘female‘, ‘age‘: 18}"   # 必须写成上面这种形式(双引号),不能使用单引号,这也是使用 json 方式的缺陷user_dict = json.loads(user_str)     # {"name" : "Kitty", "gender" : "female", "age": 18}

Way two:

user_str = ‘{"name" : "Kitty", "gender" : "female", "age": 18}‘user_dict = eval(user_str)       # {‘name‘: ‘Kitty‘, ‘gender‘: ‘female‘, ‘age‘: 18}

Tip: There is no problem with Eval to JSON, but there is a security issue with Eval, so it is not recommended to use ~

Way three:

import astuser_str = ‘{"name" : "Kitty", "gender" : "female", "age": 18}‘user_dict = ast.literal_eval(user_str)    # {‘name‘: ‘Kitty‘, ‘gender‘: ‘female‘, ‘age‘: 18}

Tip:ast.literal_eval There is no JSON problem, there is no security problem, it is recommended to use ~

Collection

A collection (set) is a sequence of unordered, non-repeating elements. only immutable objects can be stored in the collection (hash) ~

--Create a collection

Create a collection using {} or set ()

my_set = {‘python‘, ‘ruby‘, ‘java‘, ‘python‘, ‘go‘}      # 推荐使用# 或者my_set = set([‘python‘, ‘ruby‘, ‘java‘, ‘python‘, ‘go‘])my_set = set({‘python‘, ‘ruby‘, ‘java‘, ‘python‘, ‘go‘})my_set = set((‘python‘, ‘ruby‘, ‘java‘, ‘python‘, ‘go‘))# 创建的集合为:{‘python‘, ‘java‘, ‘go‘, ‘ruby‘}# 集合中不可存放可变对象>>> my_set = {[1,2,3], ‘abc‘}Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: unhashable type: ‘list‘

TIP: Because the elements in the collection are not repeatable, duplicate elements retain only one

Create an empty collection

my_set = set()      # 不能使用 {},{} 会创建一个空的字典
--Collection of common operations
# Add an element, an add () operation, if the element already exists, do nothing >>> my_set = {' Python ', ' Ruby ', ' java ', ' python ', ' Go '}>>> my_set.add ( ' C ') >>> my_set{' Go ', ' Ruby ', ' C ', ' Python ', ' Java '}# Update collection, an update operation, an existing element, no action, non-existent element to add >>> My_ set = {' Python ', ' Ruby ', ' java ', ' python ', ' Go '}>>> my_set.update ({' Go ', ' php ', ' C '}) >>> my_set{' Go ', ' Ruby ', ' C ', ' Python ', ' php ', ' java '}# delete element # Remove, remove element from collection, if not present, error ~>>> My_set = {' Python ', ' Ruby ', ' Java ', ' Pyth On ', ' Go '}>>> my_set.remove (' python ') >>> my_set{' Go ', ' Ruby ', ' Java '}>>> my_set.remove (' php ') Traceback (most recent call last): File "<stdin>", line 1, in <module>keyerror: ' php ' # Discard, remove elements from the collection, element does not exist no error >>> My_set = {' Python ', ' Ruby ', ' java ', ' python ', ' Go '}>>> my_set.discard (' Ruby ') >> > My_set.discard (' php ') >>> my_set{' go ', ' python ', ' Java '}# pop, randomly removes an element from the collection and returns the deleted element >>> My_set = {' Python ', ' Ruby ', ' java ', ' python ', ' Go '}&GT;&GT;&GT My_set.pop () ' Go ' >>> my_set{' python ', ' Ruby ', ' Java '}# compute the number of elements in the collection >>> len (my_set) 3# empty collection >>> My_set.clear () >>> my_setset () # Determines whether the collection contains an element, returns true, otherwise returns false~, and the corresponding not in>>> my_set = {' Python ', ' Ruby ', ' java ', ' python ', ' Go '}>>> ' java ' in my_settrue>>> ' Erlang ' in My_setfalse
--Set operation
>>> my_set_1 = {‘Apple‘, ‘Facebook‘, ‘Amazon‘}>>> my_set_2 = {‘Apple‘, ‘Google‘, ‘Alibaba‘}

---- Union

>>> my_set_1 | my_set_2{‘Apple‘, ‘Amazon‘, ‘Google‘, ‘Alibaba‘, ‘Facebook‘}# 对应方法>>> my_set_1.union(my_set_2){‘Apple‘, ‘Amazon‘, ‘Google‘, ‘Alibaba‘, ‘Facebook‘}

---- intersection intersection

>>> my_set_1 & my_set_2{‘Apple‘}# 对应方法>>> my_set_1.intersection(my_set_2){‘Apple‘}

---- Difference Set difference

>>> my_set_1 - my_set_2{‘Amazon‘, ‘Facebook‘}# 对应方法>>> my_set_1.difference(my_set_2){‘Amazon‘, ‘Facebook‘}

---- Symmetric difference set Sysmmetric difference

>>> my_set_1 ^ my_set_2{‘Alibaba‘, ‘Amazon‘, ‘Google‘, ‘Facebook‘}# 对应方法>>> my_set_1.symmetric_difference(my_set_2){‘Alibaba‘, ‘Amazon‘, ‘Google‘, ‘Facebook‘}

You can use Set () to convert a list,tuple,dict string into a collection

my_set = set([‘python‘, ‘ruby‘, ‘java‘, ‘python‘, ‘go‘])my_set = set((‘python‘, ‘ruby‘, ‘java‘, ‘python‘, ‘go‘))my_set = set({‘a‘:1, ‘b‘:2, ‘c‘:3})       # 仅获取 keys,转换后的集合 {‘a‘, ‘c‘, ‘b‘}my_set = set(‘abcdefg‘)                  # {‘e‘, ‘c‘, ‘f‘, ‘d‘, ‘b‘, ‘a‘, ‘g‘}

.................^_^

Python Basic data type

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.