Python list of characteristics and common methods
1. Definition of the list
Array: It is a collection of storing a plurality of the same type of data.
List: No array in python, only lists and tuples (described later). The list is "playing an array of hormones" that can store any type of data.
2. Create a list
list = [1,1.2,True,'westos']
print(list,type(list))
Output:
The list can also be nested list:
list2 = [1,2,3,4,[1,1.2,True,'westos']]
print(list2,type(list2))
Output:
3. List of properties
3.1 Index
list[num]: Forward Index
list[-num]: Reverse Index
service = ['http','ftp','ssh']
# 正向索引
print(service[0])
# 反向索引
print(service[-1])
Output:
3.2 slices
list[::-1]: Flip
list[1:]: Other elements to remove the first element of the list
list[:-1]: Remove other elements of the last element of the list
service = ['http','ftp','ssh']
print(service[::-1]) #翻转
print(service[1:]) #列表中除去第一个元素的其他元素
print(service[:-1]) #列表中除去最后一个元素的其他元素
Output:
3.3 Repeat
list * 10: Repeat 10 times Print List
service = ['http','ftp','ssh']
print(service * 10) #重复打印10遍
Output:
3.4 connection
list1 + list2: List list1 connection with the list list2, the formation of a new list
service1 = ['http','ftp','ssh']
service2 = ['mysql','firewalld']
print(service1 + service2)
Output:
3.5 member operator
service1 = ['http','ftp','ssh']
service2 = ['mysql','firewalld']
print('firewalld' in service1)
print('ftp' not in service2)
Output:
3.6 for loop
service = ['http','ftp','ssh']
for i in service:
print(i)
Output:
4. List of common methods
Increased 4.1 list elements
list.append(): Append an element to the list
list.extend(): Stretch, a plurality of elements added to the list
list.insert(): Inserts an element at the specified index
service = ['http','ftp','ssh']
# append():追加一个元素到列表
service.append('firewalld')
print(service)
# extend():拉伸 追加多个元素到列表
service.extend(['mysql','nfs'])
print(service)
# insert():在指定索引处插入元素
service.insert(1,'dns')
print(service)
Output:
4.2 Delete list elements
pop(): Pop-up list of the last element
remove(): Delete list element
of the: Remove an element from memory, del to delete variables
# pop():弹出列表最后一个元素
service = ['http','ftp','ssh']
a = service.pop()
print(a)
print(service)
# remove():删除列表元素
service = ['http','ftp','ssh']
b = service.remove('ftp')
print(b)
print(service)
# del 从内存中删除一个元素,del可删除变量
service = ['http','ftp','ssh']
del service[0] #删除列表中索引为0的元素
print(service)
Output:
4.3 View a list of elements
service = ['http','ftp','ssh','mysql','ssh','http']
# 查看元素在列表中出现的位置
print(service.count('ssh'))
# 查看指定元素的索引值
print(service.index('ssh'))
# 查看指定元素的索引值,指定搜索范围
print(service.index('ssh',3,5))
Output:
4.4 Sorting list elements
Sorting the list is sorted by default ASCII code
service = ['ftp','ssh','http','mysql','http','ssh']
service.sort(reverse=True)
print(service)
Output:
Digital Sort:
#数字升序排序
li = list(range(0,101))
print(li)
#随机排序
import random
random.shuffle(li)
print(li)
Output: