Python2 study notes (3)

list

A built-in list of data types in Python is an ordered collection. You can add and delete elements at any time.

  • A list is an ordered collection, written in square brackets.
>>> name
['a', 'b', 'c']
>>> grade = [12,34,10]
>>> grade
[12, 34, 10]
  • The length len()that can be obtained with the functionlist
>>> len(grade)
3
>>> a =[] #空的list,长度为0
>>> len(a)
0
  • Accessing listelements can be indexed
>>> name[0]  #索引从0开始
'a'
>>> name[2]
'c'
>>> name[3] #下标越界,最后一个元素的索引是len(name)-1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> name[-1] #以负数作索引,可以从后边倒着访问list中的元素
'c'
>>> name[-3]
'a'
  • Insert element【append, insert
>>> name.append('d') #使用 append 函数追加元素到list后边
>>> name
['a', 'b', 'c', 'd']
>>> name.insert(1,'A')#使用 intert 函数在指定索引处增加元素,其余元素向后移动
>>> name
['a', 'A', 'b', 'c', 'd']
  • Delete element【pop, pop(i)
>>> name.pop() #使用 pop 函数删除末尾的元素
'd'
>>> name
['a', 'A', 'b', 'c']
>>> name.pop(0) #使用 pop(i) 函数删除指定位置的元素
'a'
>>> name
['A', 'b', 'c']
  • Replace element (assign a new value directly to the specified position)
>>> name
['A', 'b', 'c']
>>> name[2] = 'B'
>>> name
['A', 'b', 'B']
  • Different data types can exist in the list
>>> student_infortation = ['liming',18,True,[56,87,89,50]]
>>> student_infortation
['liming', 18, True, [56, 87, 89, 50]]
>>> student_infortation[3]
[56, 87, 89, 50]
>>> student_infortation[-1][1]#查看元素的元素
87

tuple

It is an ordered list called a tuple, which cannot be modified once initialized

  • Enclosed in parentheses to indicate element resistance
>>> country = ('china','shannxi','beijing') 
>>> country
('china', 'shannxi', 'beijing')
>>> team = ('abc',16,True) #可以存在不同的数据类型
>>> team
('abc', 16, True)
>>> t = () #空的元组
>>> t
()
>>> len(t)
0

Note: There is only one element in the element resistance

>>> t = (3) #这种实际上是定义了数字3,因为圆括号又表示数学公式中的小括号,这里python规定按小括号进行计算
>>> t
3
>>> t = (3,) #python中定义一个元阻元素要在其后边加上逗号,且输出这一个元素也要在其后面加逗号,来消除歧义
>>> t
(3,)
>>> len(t)
1
  • The tuple element point never changes
>>> team
('abc', 16, True)
>>> team[1]    #查看元素,用索引
16
>>> team[1]=3  #元素不可更该
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> group = ('zhangsan',[23,45,67,89])
>>> group[1][2] = 66   #元组中list的元素更改。更改的实际上是list的元素的指向,但元组依旧指向该list没有发生改变
>>> group
('zhangsan', [23, 45, 66, 89])

Guess you like

Origin blog.csdn.net/jjt_zaj/article/details/51533113