List,tuple,dict and set
1.list Collection
A list is a mutable , ordered set of elements that can be added and removed at any time.
The format is as follows:List-name=[element1,element2,....]
>>> nums = [' 1 ', ' 2 ', ' 3 ']
>>> Nums
[' 1 ', ' 2 ', ' 3 ']
1.1获取list元素的个数:len(list-name)
>>> Len (nums)
3
1.2 Accessing elements by index ( index starting from 0, counting from-1 )
>>>nums[0]
' 1 '
>>>nums[-2]
' 2 '
1.3 Adding elements
1.3.1 add element at the end:list-name.append (value)
>>> nums.append (' 4 ')
>>> Nums
[' 1 ', ' 2 ', ' 3 ', ' 4 ']
1.3.2 add element at specified location:list-name.insert (index, value)
>>> Nums.insert (1, ' 1.5 ')
>>> Nums
[' 0 ', ' 1.5 ', ' 1 ', ' 2, ' 3 ', ' 4 ']
1.4 Delete the element at the end:list-name.pop ()
>>> Nums.pop ()
>>> Nums
[' 0 ', ' 1.5 ', ' 1 ', ' 2, ' 3 ']
1.5 Delete the element at the specified location:list-name.pop (index)
>>> Nums.pop (1)
>>> Nums
[' 0 ', ' 1 ', ' 2, ' 3 ']
1.6 Replacement elements:list-name[index]=value
>>> nums[1] = ' 1.5 '
>>> Nums
[' 0 ', ' 1.5 ', ' 2 ', ' 3 ']
1.7 element types can be inconsistent, and can be nested
>>> p = [' 1 ', ' 2 ']
>>> s = [' A ', ' B ', p, ' C ']
2.tuple Collection
The tuple and list are very similar, but the tuple cannot be modified once it is initialized .
The format is as follows:tuple-name= (Element1,element2,...)
A variable tuple:
>>> t = (' A ', ' B ', [' A ', ' B '])
>>> t[2][0] = ' X '
>>> t[2][1] = ' Y '
>>> T
(' A ', ' B ', [' X ', ' Y '])
The list collection is nested here, because the elements in the list are changed, regardless of the tuple.
3.dict Collection
Dict Full Name Dictionary (dictionary), also known as map in other languages, is stored using key-value (Key-value) and has a very fast lookup speed.
The Dict key must be an immutable object.
In Python, strings, integers, and so on are immutable and can be used as keys.
The format is as follows:dict-name={key1:value1,key2:value2,...}
>>> age = {' Tom ': ' Jack ': +, ' jim ': 15}
>>> Age
{' Tom ': ' Jack ': +, ' jim ': 15}
3.1 Viewing elements:dict-name.get (key)
>>> d.get (' Thomas ')
14
When key does not exist, the return value is none.
3.2 Update elements:dict-name[key]=value
>>> age[' tom '] = 10
>>> age.get (' Tom ')
10
3.3 Deleting elements:Dict-name.pop (key)
>>> age.pop (' Tom ')
>>> Age
{' Jack ': +, ' jim ': 15}
4.set Collection
Set is similar to Dict and is a set of keys , but does not store value. Because key cannot be duplicated, there is no duplicate keyin set.
To create a set, you need to provide a list as the input collection :
The format is as follows:Set-name=set ([list-name])
>>> s = Set ([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}
4.1 Adding elements:set-name.add (key)
>>> S.add (4)
>>> s
{1, 2, 3, 4}
4.2 Removing elements:set-name.remove (key)
>>> S.remove (4)
>>> s
{1, 2, 3}
Python Learning Note 3