Python - getting started with containers

1. List

     List is the most commonly used Python data type, and it can appear as a comma-separated value in square brackets. The data items of the list need not have the same type

     To create a list, simply enclose the different data items separated by commas in square brackets. As follows

list1 = ['txj', 'zwh', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']

   1.1 Access to the values ​​in the list

        A list is an ordered collection, so to access any element of the list, you only need to tell Python the position or index of the element. To access a list element, you can specify the name of the list, then the index of the element, and put it in square brackets.   

number = [1, 2, 3, 4]
print(number[0])
print(number[1])

      Note that the index starts from 0, not 1

      Python provides a special syntax for accessing the last list element. By specifying the index as -1, Python can return the last list element, and so on, -2 means the penultimate element, -3 means the penultimate 3 elements

number = [1, 2, 3, 4]
print(number[-1])
print(number[-2])

1.2, modify, add and delete elements

    1.2.1, modification

    The syntax for modifying list elements is similar to that for accessing list elements. To modify a list element, you can specify the list name and the index of the element to be modified, and then specify the new value of the element. 

number = [1, 2, 3, 4]
number[0] = 100
print(number)

   1.2.2, add

     (1) Adding elements to the end of
              the list When adding new elements to the list, the easiest way is to append the elements to the end of the list. When you append an element to the list, it will be added to the end of the list. You can use the append() method.             

number = [1, 2, 3, 4]
list.number(100)
print(number)

  (2) Insert elements in the list
           Use the insert() method to add new elements at any position in the list. Therefore, you need to specify the index and value of the new element.

number = [1, 2, 3, 4]
list.number(0, 100)
print(number)

1.2.3, delete

     (1) Use del statement to delete elements
              If you know the position of the element to be deleted in the list, you can use the del statement. Note that if you delete an element using the del statement, you will not be able to access the element again.          

number = [1, 2, 3, 4]
del number[0]
print(number)

    (2) Use pop() to delete elements

             The method pop() deletes the element at the end of the list and allows you to continue using it. The term pop comes from the analogy: a list is like a stack, and deleting the element at the end of the list is equivalent to popping the top element.        

number = [1, 2, 3, 4]
number.pop()
print(number)

   (3) Pop-up elements at any position of the list

           In fact, you can use pop() to delete an element at any position in the list, just specify the index of the element to be deleted in parentheses.

number = [1, 2, 3, 4]
number.pop(0)
print(number)

(4) Delete elements based on value

        Sometimes, you don't know where the value you want to remove from the list is. If you only know the value of the element to be deleted, you can use the method remove().

        Note: The method remove() only deletes the first specified value. If the value to be deleted may appear multiple times in the list, you need to use a loop to determine whether all such values ​​have been deleted.

number = [1, 2, 3, 4]
number.remove(3)
print(number)

1.3, list functions and methods

        Python contains the following functions:

Serial number function
1 len(list) the
number of list elements
2 max(list)
returns the maximum value of list elements
3 min(list)
returns the minimum value of list elements
4 list(seq)
convert a tuple to a list

       Python contains the following methods:

Serial number method
1 list.append(obj)
adds a new object at the end of the list
2 list.count(obj)
counts the number of times an element appears in the list
3 list.extend(seq)
appends multiple values ​​in another sequence at the end of the list (extend the original list with the new list)
4 list.index(obj)
Find the index position of the first matching item of a certain value from the list
5 list.insert(index, obj)
insert the object into the list
6 list.pop([index=-1])
removes an element from the list (the last element by default), and returns the value of the element
7 list.remove(obj)
removes the first match of a value in the list
8 list.reverse()
reverse the elements in the list
9 list.sort( key=None, reverse=False)
sort the original list
10 list.clear()
clear the list
11 list.copy()
copy list

  2. Set

       A set is an unordered sequence of non-repeating elements.

       You can use braces {} or set() to create a collection. Note: To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary.

   

>>> number = {1, 2, 3, 2, 4, 5}
>>> print(number)                      # 这里演示的是去重功能
{1, 2, 3, 4, 5}
>>> 1 in number                # 快速判断元素是否在集合内
True
>>> 6 in basket
False

>>> # 下面展示两个集合间的运算.
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # 集合a中包含而集合b中不包含的元素
{'r', 'd', 'b'}
>>> a | b                              # 集合a或b中包含的所有元素
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # 集合a和b中都包含了的元素
{'a', 'c'}
>>> a ^ b                              # 不同时包含于a和b的元素
{'r', 'd', 'b', 'm', 'z', 'l'}

  2.1, the basic operation of the collection

       2.1.1, add elements

               (1) You can use the add() method. If the added element already exists, no operation is performed.         

number = set((1, 2, 3, 4))
number.add(5)
print(number)

              (2) There is another method, you can also add elements, and the parameters can be lists, tuples, dictionaries, etc.

number = set((1, 2, 3, 4))
number.update('a', "b")
print(number)
number.update([7, 8], [9, 0])
print(number)

2.1.2, remove elements

           (1) Use the remove() method to remove the element x from the set s. If the element does not exist, an error will occur.        

number = set((1, 2, 3, 4))
number.remove(1)
print(number)

           (2) Using discard() method can also remove elements in the collection, and if the element does not exist, no error will occur.

number = set((1, 2, 3, 4))
number.discard(1)
print(number)

          (3) We can also use the pop() method to randomly delete an element in the set. The pop() method of the set collection will arrange the collection in an unordered manner, and then delete the first element on the left of the unordered collection.

number = set((1, 2, 3, 4))
number.pop()
print(number)

2.1.3, calculate the number of elements

           Just use the len() method.

number = set((1, 2, 3, 4))
length = len(number)
print(length)

2.2, a complete list of collection built-in methods

method description
add() Add elements to the collection
clear() Remove all elements in the collection
copy() Copy a collection
difference() Returns the difference of multiple sets
difference_update() Remove the element in the collection, the element also exists in the specified collection.
discard() Delete the specified element in the collection
intersection() Returns the intersection of sets
intersection_update() Returns the intersection of sets.
isdisjoint () Determine whether the two collections contain the same element, if not return True, otherwise return False.
issubset() Determine whether the specified set is a subset of the method parameter set.
issuperset() Determine whether the parameter set of the method is a subset of the specified set
pop() Randomly remove elements
remove() Remove specified element
symmetric_difference() Returns a collection of elements that are not repeated in the two collections.
symmetric_difference_update() Remove the same elements in another specified set in the current set, and insert different elements in another specified set into the current set.
union() Returns the union of two sets
update() Add elements to the collection

3. Tuple

     Python tuples are similar to lists, except that the elements of tuples cannot be modified. Use parentheses () for tuples and square brackets [] for lists.

     Tuple creation is very simple, just add elements in parentheses and separate them with commas.

tup1 = ('b', 'b', 2020, 2021)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"   #  不需要括号也可以

     Create empty tuple

tup = ()

     When the tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators:

>>> tup1 = (1)
>>> type(tup1)     # 不加逗号,类型为整型
<class 'int'>

>>> tup1 = (1,)
>>> type(tup1)     # 加上逗号,类型为元组
<class 'tuple'>

 3.1, visit tuple

          Tuples can use the subscript index to access the values ​​in the tuple, as in the following example:    

tup1 = ('a', 'b', 2020, 2021)
tup2 = (1, 2, 3, 4, 5, 6, 7)

print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])

  3.2, modify the tuple

           The element value in the tuple is not allowed to be modified, but we can connect and combine the tuple, as in the following example:

tup1 = ('a', 'b', 2020, 2021)
tup2 = (1, 2, 3, 4, 5, 6, 7)
tup3 = tup1 + tup2
print(tup3)

3.3, delete tuples

        The element value in the tuple is not allowed to be deleted, but we can use the del statement to delete the entire tuple, as in the following example:

tup1 = ('a', 'b', 2020, 2021)
del tup1
print(tup1) 

  After the above instance tuple is deleted, the output variable will have abnormal information.

3.4, tuple operator

        Like character strings, you can use + and * to perform operations between tuples.

Python expression result description
len((1, 2, 3)) 3 计算元素个数
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 连接
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') 复制
3 in (1, 2, 3) True 元素是否存在
for x in (1, 2, 3): print (x,) 1 2 3 迭代

3.5、元组内置函数

python元组包含了以下内置函数

序号 方法及描述 实例
1 len(tuple)
计算元组元素个数。
>>> tuple1 = ('Google', 'Runoob', 'Taobao')
>>> len(tuple1)
3
>>> 
2 max(tuple)
返回元组中元素最大值。
>>> tuple2 = ('5', '4', '8')
>>> max(tuple2)
'8'
>>> 
3 min(tuple)
返回元组中元素最小值。
>>> tuple2 = ('5', '4', '8')
>>> min(tuple2)
'4'
>>> 
4 tuple(iterable)
将可迭代系列转换为元组。
>>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')

4、字典

     字典是另一种可变容器模型,且可存储任意类型对象。

     字典的每个键值 key=>value 对用冒号 : 分割,每个对之间用逗号(,)分割,整个字典包括在花括号 {} 中 ,格式如下所示:

     键必须是唯一的,但值则不必。

    值可以取任何数据类型,但键必须是不可变的,如字符串,数字。 

dict = {'name': 'txj', 'numbers': 123, 'hobbby': 'eat'}

  4.1、访问字典的元素。

dict = {'Name': 'txj', 'Age': 20, 'hobby': 'eat'}
 
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

    如果用字典里没有的键访问数据,会输出错误。

 4.2、添加键值对

alien_0 = {'color': 'green', 'points': '5'}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

4.3、删除键值对

        能删单一的元素也能清空字典,清空只需一项操作。

dict = {'Name': 'txj', 'Age': 20, 'hobby': 'eat'}
del dict['Name']  # 删除键 'Name'
dict.clear()      # 清空字典
del dict          # 删除字典
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])

   但这会引发一个异常,因为用执行 del 操作后字典不再存在

4.4、字典键的特性

       (1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住。

       (2)键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行。

4.5、字典内置函数和方法

Python字典包含了以下内置函数:

序号 函数及描述 实例
1 len(dict)
计算字典元素个数,即键的总数。
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> len(dict)
3
2 str(dict)
输出字典,以可打印的字符串表示。
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> str(dict)
"{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
3 type(variable)
返回输入的变量类型,如果变量是字典就返回字典类型。
>>> dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
>>> type(dict)
<class 'dict'>

Python字典包含了以下内置方法:

序号 函数及描述
1 radiansdict.clear()
删除字典内所有元素
2 radiansdict.copy()
返回一个字典的浅复制
3 radiansdict.fromkeys()
创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4 radiansdict.get(key, default=None)
返回指定键的值,如果键不在字典中返回 default 设置的默认值
5 key in dict
如果键在字典dict里返回true,否则返回false
6 radiansdict.items()
以列表返回可遍历的(键, 值) 元组数组
7 radiansdict.keys()
返回一个迭代器,可以使用 list() 来转换为列表
8 radiansdict.setdefault(key, default=None)
和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9 radiansdict.update(dict2)
把字典dict2的键/值对更新到dict里
10 radiansdict.values()
返回一个迭代器,可以使用 list() 来转换为列表
11 pop(key[,default])
删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12 popitem()
随机返回并删除字典中的最后一对键和值。

 

Guess you like

Origin blog.csdn.net/Light20000309/article/details/112745738