News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

2024-11(8)

Python 列表list详解(超详细)

posted on 2023-05-07 20:24     read(468)     comment(0)     like(0)     collect(2)


Detailed explanation of Python built-in functions/methods - list list

A list is an ordered and mutable collection, and is the most commonly used Python data type. In Python, lists are []written .

1. Create a list

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.

1.1 Use [ ] to create a list

To create a list, just enclose the different data items separated by commas with square brackets [] .

  • create empty list
list0 = []
  • create non-empty list
list1 = ['Baidu', 'Alibaba', 'Tencent']

1.2 Use the list() function to create (convert to) a list

  • Lists can be created using the list() constructor:
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 .

  • In Python, we can convert other similar objects like strings, tuples, dictionaries, and sets into lists using the list() function. See the following built-in functions for specific usage:

2. Access list

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).

2.1 Subscript index access

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)...

2.2 Slice access

If you don't understand the above description, you can refer to the following table:

tuple valueetclglgzwhlsjhxw
forward index012345
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.

2.3 for loop to traverse the list

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

2.4 Check if the project exists

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 .

2.5 Changing List Values

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.

2.6 List join (merge)/copy

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']

2.7 Nested lists

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']]

2.8 List comparison

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

3. Built-in functions

3.1 Print output print()

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]

3.2 Determine list item len()

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.3 return variable type type()

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_listusing type() to determine the variable type, it will return <class 'list'>, indicating that this is a list .

3.4 Convert to list list()

4. tuple()Function

The function of the tuple() function is to convert other types into tuple types. The detailed usage is as follows:

  • convert string to list
str1 = 'Hello Python'
print(list(str1))
['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
  • convert tuple to list
tuple1 = ('Hello', 'Python')
print(list(tuple1))
['Hello', 'Python']
  • convert dictionary to list
dict1 = {'Hello': 'Python', 'name': 'pink'}
print(list(dict1))
['Hello', 'name']
  • convert collection to list
set1 = {'Hello', 'Python', 'name', 'pink'}
print(list(set1))
['Python', 'name', 'pink', 'Hello']
  • convert range to list
range1 = range(1, 6)
print(list(range1))
[1, 2, 3, 4, 5]

3.5 The maximum/minimum value of tuple elements max(), min()

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

3.6 delete list del

  • delete a single element

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']
  • delete list

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.

4. Built-in methods

4.1 Add elements append(), insert(), extend()

1. append()Method

The append() method is used to add new objects at the end of the list.

grammar

list.append(element)

parameter value

parameterdescribe
elementrequired. Elements of any type (string, number, object, etc.).

example

  • add element
fruit_list = ['apple', 'banana', 'cherry']
fruit_list.append('pear')
print(fruit_list)
['apple', 'banana', 'cherry', 'pear']
  • add list
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

parameterdescribe
positionrequired. A number specifying where to insert the value.
elementrequired. Element, of any type (string, number, object, etc.).

example

  • Insert the value "orange" as the second element into the fruits list:
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
['apple', 'orange', 'banana', 'cherry']
  • insert list y into list x
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

parameterdescribe
iterablerequired. Any iterable object (list, set, tuple, etc.).

example

aver = ['A', 'B', 'C']
  • Adds string elements to the end of the list
str1 = 'Hello'
aver.extend(str1)
print(aver)
['A', 'B', 'C', 'H', 'e', 'l', 'l', 'o']
  • Add list element to the end of the list
list1 = [1, 2, 3]
aver.extend(list1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
  • Add tuple elements to the end of the list
tuple1 = (1, 2, 3)
aver.extend(tuple1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
  • Add dictionary elements to the end of the list
dict1 = {'name': 'pink', 'gender': True}
aver.extend(dict1)
print(aver)
['A', 'B', 'C', 'name', 'gender']
  • Add collection elements to the end of the list
set1 = {1, 2, 3}
aver.extend(set1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
  • add range to end of list
range1 = range(1,10)
aver.extend(range1)
print(aver)
['A', 'B', 'C', 1, 2, 3, 4, 5, 6, 7, 8, 9]

4.2 Element occurrence count()

The count() method is used to count the number of times an element appears in the list.

grammar

list.count(value)

parameter value

parameterdescribe
valuerequired. 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

4.3 Specify the value index index()

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

parameterdescribe
elementrequired. 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.

4.4 Sorting a list sort()

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

parameterdescribe
reverseoptional. reverse=True will sort the list in descending order. The default is reverse=False.
keyoptional. A function that specifies sorting criteria.

example

  • Sort the list alphabetically:
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” 值对字典列表进行排序:
# 返回 '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)]

4.5 复制列表 copy()

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)

4.6 颠倒列表顺序 reverse()

reverse() 方法用于反向列表中元素。

语法

list.reverse()

参数值

无参数

实例

fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
['cherry', 'banana', 'apple']

4.7 删除元素 pop()、remove()、clear()

1、pop()方法

pop() 方法用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。

语法

list.pop(pos)

参数值

参数描述
pos可选。数字,指定需删除元素的位置。默认值 -1,返回最后的项目。

实例

  • pos 未指定时,默认删除最后的元素
fruits = ['apple', 'banana', 'cherry']
fruits.pop()
print(fruits)
['apple', 'banana']
  • pos 指定要删除元素的位置
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..

5. Summary

functiondescribe
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 thedelete list
methoddescribe
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



Category of website: technical article > Blog

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.

0 0
collect article
collected

Comment content: (supports up to 255 characters)