Understanding Python in one article (1)-----lists and tuples

1. List

1.1 Create a list

member = ['胖虎','大熊','小夫','小叮当','小妹妹']
member

1.2 Create a mixed list

mix = [1,'胖虎','3.14',[1,2,3]]
mix

1.3 Create an empty list

empty = []
empty

1.4 Add elements to the list

1.4.1 append(sub): Add an element sub at the end of the list

member.append('董金琨')
member

1.4.2 extend(list): add another list to the original list, extend another list with one list, list is a list type

member.extend(['胖虎他妈','大熊她爸'])
member

1.4.3 insert(i,x) function: add element x at the i-th position

member.insert(1,'小夫她爹')
member

1.5 Get the elements in the list

member[0]

1.6 Delete elements in the list

1.6.1 del method

# 删除指定位置元素
del member[1]
# 删除整个列表
del member 

1.6.2 remove(x): delete the x element in the list, x must be in the list, no error will be reported

# remove(元素):该元素必须在列表中
member.remove('胖虎')
member

1.6.3 pop(i): delete the element at the i-th position

member.pop(i)
member

1.7 List repeat operator

# 该操作不会影响原列表
list3 = [123,456]
list3*5

1.8 List commonly used built-in functions

1.8.1 count(x): View the number of times the parameter x appears in the list

list3 = [123,456,789]
list3 *= 5
list3.count(123)

1.8.2 index(x,[[start],[end]]): Returns the position of parameter x in the list, start and end are optional.

list3.index(123,3,7)

1.8.3 reverse(): Reverse the list

list3.reverse()
list3

1.8.4 sort(): sort the list, the default is from small to large

# sort()函数会改变原列表
list6 = [4,5,2,3,1,10]
list6.sort()
list6
# 从大到小排序
list7 = [7,8,5,2,7,8,9]
list7.sort(reverse = True)
list7

Two, tuple

2.1 Create an ordinary tuple

tuple1 = (1,2,3,4,5,6,7,8)
tuple1

2.2 Create a tuple with only one element

tuple3 = (1,)
tuple3

2.3 Update and modify tuples

# 原temp还存在,但是没有变量名指向它
temp = ('大熊','小夫','大P','小米')
temp = temp[:2] + ('小景',)+temp[2:]
temp

2.4 delete tuples

del temp

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/112673743