posted on 2023-05-07 20:24 read(468) comment(0) like(0) collect(2)
A list is an ordered and mutable collection, and is the most commonly used Python data type. In Python, lists are []
written .
In Python, the data types of elements in a list can be different, including integers, floating-point numbers, and complex numbers. Of course, lists, tuples, dictionaries, and sets can also be included.
To create a list, just enclose the different data items separated by commas with square brackets [] .
list0 = []
list1 = ['Baidu', 'Alibaba', 'Tencent']
this_list = list(('apple', 'banana', 'cherry'))
Note: When using the list() function to create a list, be sure to pay attention to the double brackets .
Like lists, we can either use subscripts to access an element in the list (to get the value of an element), or use slices to access a set of elements in the list (to get a sublist).
Subscript index access tuples are divided into two categories, namely forward index and reverse index . The format is list_name[i]
, where list_name represents the list name, i represents the index value, and i can be a positive number (forward index) or a negative number ( inverted index).
It can be known that the first element of list_name[0]
the list represents the last element of the list .list_name[-1]
list_name = ['wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw']
print(list_name[0])
print(list_name[-1])
wzq
hxw
Forward index: start from the first (subscript 0), second (subscript 1)...
Reverse index: from the first to last (subscript -1), second to last (subscript -2)...
If you don't understand the above description, you can refer to the following table:
tuple value | etc | lgl | gz | whl | sj | hxw |
---|---|---|---|---|---|---|
forward index | 0 | 1 | 2 | 3 | 4 | 5 |
inverted index | -6 | -5 | -4 | -3 | -2 | -1 |
The format of using a slice to access the list is list_name[strat : end : step]
, where start indicates the start index, end indicates the end index, and step indicates the step size.
list_name = ['wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw']
print(list_name[1:5:2])
print(list_name[-6:-1:3])
['lgl', 'whl']
['wzq', 'whl']
When using slices to access list elements,
list_name[strat : end : step]
[start: end] is a left-closed right-open interval, that is, the element represented by end cannot be accessed.
The items in a list can be iterated over using a for loop:
fruit_list = ['apple', 'pear', 'cherry']
for i in fruit_list:
print(i)
apple
pear
cherry
To determine whether a specified item exists in the list, we can use the in keyword:
# 检查列表中是否存在'apple'
fruit_list = ['apple', 'pear', 'cherry']
print('apple' in fruit_list)
True
When using the in keyword to check whether the specified item exists in the list, if it exists, it returns True ; otherwise, it returns False .
When we create a list, we can modify or update the data items in the list. Of course, we can also use the append() method to add list items.
fruit_list = ['apple', 'pear', 'cherry']
fruit_list[2] = 'banana'
print(fruit_list)
['apple', 'pear', 'banana']
Note: Once a tuple is created, its value cannot be changed, but there are other workarounds.
Like strings, tuples can +
be concatenated and copied*
between lists using the and signs , which means they can generate a new list.
1. +
Connection (merge)
x = [1, 2, 3]
y = [4, 5, 6]
print(x + y)
[1, 2, 3, 4, 5, 6]
2. *
Copy
x = ['Hello']
print(x * 5)
['Hello', 'Hello', 'Hello', 'Hello', 'Hello']
Use nested lists to create other lists inside lists.
x = [1, 2, 3]
y = ['a', 'b', 'c']
z = [x, y]
print(z)
[[1, 2, 3], ['a', 'b', 'c']]
List comparison needs to introduce the eq method of the operator module .
# 导入 operator 模块
import operator
a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a, b):", operator.eq(a, b))
print("operator.eq(b, c):", operator.eq(b, c))
operator.eq(a, b): False
operator.eq(b, c): True
1. print()
Function
We are already very familiar with the function of the print() function, which is to print the output.
my_list = ['pink', True, 1.78, 65]
print(my_list)
['pink', True, 1.78, 65]
2. len()
Function
Functions are used when we want to determine how many items (elements) a list has len()
.
fruit_list = ['apple', 'banana', 'cherry']
print(len(fruit_list))
3
3. type()
Function
Use the type() function to determine what type a variable is (string, list, tuple, dictionary, or set).
info_list = ['name', 'gender', 'age', 'height', 'weight']
print(type(info_list))
<class 'list'>
When
info_list
using type() to determine the variable type, it will return<class 'list'>
, indicating that this is a list .
4. tuple()
Function
The function of the tuple() function is to convert other types into tuple types. The detailed usage is as follows:
str1 = 'Hello Python'
print(list(str1))
['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
tuple1 = ('Hello', 'Python')
print(list(tuple1))
['Hello', 'Python']
dict1 = {'Hello': 'Python', 'name': 'pink'}
print(list(dict1))
['Hello', 'name']
set1 = {'Hello', 'Python', 'name', 'pink'}
print(list(set1))
['Python', 'name', 'pink', 'Hello']
range1 = range(1, 6)
print(list(range1))
[1, 2, 3, 4, 5]
5. max()
Functions and min()
functions
The function of max() is to return the maximum value of the elements in the list . The function of min() is to return the minimum value of the elements in the list .
list1 = [4, 6, 2, 0, -5]
print(max(list1))
print(min(list1))
list2 = ['a', 'z', 'A', 'Z']
print(max(list2))
print(min(list2))
6
-5
z
A
We can use del list_name[i]
to delete a specified element, where list_name represents the list name, and i represents the index value of the specified value.
list_de = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance']
del list_de[1]
print(list_de)
['Baidu', 'Tencent', 'Bytedance']
The del function can not only delete a certain element, but also delete the entire list.
list_de = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance']
del list_de
When we use the del function to delete a list, and then use the print() function to print out, an error will be reported
NameError: name 'list_de' is not defined
, indicating that the list is not defined.
1. append()
Method
The append() method is used to add new objects at the end of the list.
grammar
list.append(element)
parameter value
parameter | describe |
---|---|
element | required. Elements of any type (string, number, object, etc.). |
example
fruit_list = ['apple', 'banana', 'cherry']
fruit_list.append('pear')
print(fruit_list)
['apple', 'banana', 'cherry', 'pear']
x = [1, 2, 3]
y = ['A', 'B', 'C']
x.append(y)
print(x)
[1, 2, 3, ['A', 'B', 'C']]
2. insert()
Method
The insert() method is used to insert the specified object into the specified position of the list.
grammar
list.insert(position, element)
parameter value
parameter | describe |
---|---|
position | required. A number specifying where to insert the value. |
element | required. Element, of any type (string, number, object, etc.). |
example
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
['apple', 'orange', 'banana', 'cherry']
x = [1, 2, 3]
y = ['a', 'c']
x.insert(0, y)
print(x)
[['a', 'c'], 1, 2, 3]
append() can only add elements or lists at the end , and insert() can add elements or lists at any position .
3. extend()
Method
The extend() method is used to append multiple values from another sequence at the end of the list at once (extending the original list with the new list).
grammar
list.extend(iterable)
parameter value
parameter | describe |
---|---|
iterable | required. Any iterable object (list, set, tuple, etc.). |
example
aver = ['A', 'B', 'C']
str1 = 'Hello'
aver.extend(str1)
print(aver)
['A', 'B', 'C', 'H', 'e', 'l', 'l', 'o']
list1 = [1, 2, 3]
aver.extend(list1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
tuple1 = (1, 2, 3)
aver.extend(tuple1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
dict1 = {'name': 'pink', 'gender': True}
aver.extend(dict1)
print(aver)
['A', 'B', 'C', 'name', 'gender']
set1 = {1, 2, 3}
aver.extend(set1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
range1 = range(1,10)
aver.extend(range1)
print(aver)
['A', 'B', 'C', 1, 2, 3, 4, 5, 6, 7, 8, 9]
The count() method is used to count the number of times an element appears in the list.
grammar
list.count(value)
parameter value
parameter | describe |
---|---|
value | required. Any type (string, number, list, tuple, etc.). The value to search for. |
example
num = [1, 4, 2, 9, 7, 8, 9, 3, 1]
print(num.count(9))
2
The index() method is used to find the index position of the first occurrence of a value from the list.
grammar
list.index(element)
parameter value
parameter | describe |
---|---|
element | required. Any type (string, number, list, etc.). The value to search for. |
example
num = [4, 55, 64, 32, 16, 32]
print(num.index(32))
3
When the searched value occurs multiple times in the list, only the first occurrence is returned.
The sort() method is used to sort the original list. If parameters are specified, the comparison function specified by the comparison function is used.
grammar
list.sort(reverse=True|False, key=myFunc)
parameter value
parameter | describe |
---|---|
reverse | optional. reverse=True will sort the list in descending order. The default is reverse=False. |
key | optional. A function that specifies sorting criteria. |
example
words = ['Name', 'Gender', 'Age', 'Height', 'Weight']
words.sort()
print(words)
['Age', 'Gender', 'Height', 'Name', 'Weight']
words = ['Name', 'Gender', 'Age', 'Height', 'Weight']
words.sort(reverse=True)
print(words)
['Weight', 'Name', 'Height', 'Gender', 'Age']
# 返回值的长度的函数:
def myfunc(e):
return len(e)
words = ['a', 'bb', 'ccc', 'dddd', '']
words.sort(key=myfunc)
print(words)
['', 'a', 'bb', 'ccc', 'dddd']
# 返回 'year' 值的函数:
def myfunc(e):
return e['year']
words = [
{'char': 'a', 'year': 1963},
{'char': 'b', 'year': 2010},
{'char': 'c', 'year': 2019}
]
words.sort(key=myfunc)
print(words)
[{'char': 'a', 'year': 1963}, {'char': 'b', 'year': 2010}, {'char': 'c', 'year': 2019}]
# 返回值的长度的函数:
def myfunc(e):
return len(e)
words = ['aa', 'b', 'ccc', 'dddd']
words.sort(reverse=True, key=myfunc)
print(words)
['dddd', 'ccc', 'aa', 'b']
# 获取列表的第二个元素
def takeSecond(elem):
return elem[1]
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# 指定第二个元素排序
random.sort(key=takeSecond)
# 输出类别
print('排序列表:', random)
排序列表: [(4, 1), (2, 2), (1, 3), (3, 4)]
copy() 方法用于复制列表,类似于 a[:]。
语法
list.copy()
参数值
无参数
实例
fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
print(x)
['apple', 'banana', 'cherry', 'orange']
复制(制作副本)的另一种方法是使用内置函数 list() ,如下:
list1 = ['apple', 'banana', 'cherry']
list_2 = list(list1)
reverse() 方法用于反向列表中元素。
语法
list.reverse()
参数值
无参数
实例
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
['cherry', 'banana', 'apple']
1、pop()
方法
pop() 方法用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
语法
list.pop(pos)
参数值
参数 | 描述 |
---|---|
pos | 可选。数字,指定需删除元素的位置。默认值 -1,返回最后的项目。 |
实例
fruits = ['apple', 'banana', 'cherry']
fruits.pop()
print(fruits)
['apple', 'banana']
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
['apple', 'cherry']
2、remove()
方法
remove() 方法用于移除列表中某个值的第一个匹配项。
语法
list.remove(element)
参数值
参数 | 描述 |
---|---|
element | 必需。需删除的任何类型(字符串、数字、列表等)的元素。 |
实例
num = [1, 3, 2, 8, 3]
num.remove(3)
print(num)
[1, 2, 8, 3]
当被删除的元素在列表中存在多个时,默认删除首次出现的那个。
3、clear()
方法
clear() 方法用于清空列表,类似于 del a[:]。
语法
list.clear()
参数值
无参数
实例
word = ['A', 'B', 'C']
word.clear()
print(word)
[]
The function of the clear() method is to clear the list. When the print() is used to print the output after the execution, it will output
[]
, indicating that the list still exists, but it is just an empty list .The role of the del function is to delete the list. When the print() is used to print the output after the execution, an error will be reported
NameError: name 'word' is not defined.
.
function | describe |
---|---|
print() | printout |
only() | OK list item |
type() | return variable type |
list() | convert to list |
max() | Returns the maximum value of a list element |
min() | Returns the minimum value of a list element |
of the | delete list |
method | describe |
---|---|
append(obj) | Add new object at the end of the list |
insert(index, obj) | Add element at specified position |
extend(seq) | Adds list elements (or any iterable) to the end of the current list |
count(obj) | Count the number of times an element appears in a list |
index(obj) | Returns the index of the first element with the specified value |
sort( key=None, reverse=False) | Sort the original list |
copy() | copy list |
reverse() | reverse the order of the list |
pop([-1]) | Remove an element in the list (the last element by default), and return the value of the element |
remove(obj) | removes the first occurrence of a value in a list |
clear() | clear the list |
The above is the whole content of this article! If it is helpful to you, please like it! Favorite it! Welcome to leave a message in the comment area! ! !
Last edited at: 2023/1/4 20:22
Author:gfg
link:http://www.pythonblackhole.com/blog/article/340/2e68a93e0b1fbe67eb85/
source:python black hole net
Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.
name:
Comment content: (supports up to 255 characters)
Copyright © 2018-2021 python black hole network All Rights Reserved All rights reserved, and all rights reserved.京ICP备18063182号-7
For complaints and reports, and advertising cooperation, please contact vgs_info@163.com or QQ3083709327
Disclaimer: All articles on the website are uploaded by users and are only for readers' learning and communication use, and commercial use is prohibited. If the article involves pornography, reactionary, infringement and other illegal information, please report it to us and we will delete it immediately after verification!