This article mainly introduces the advanced functions of list in python in detail. Interested friends can refer to it
use a list as a stack: #Like Use a list like a stack
stack = [3, 4, 5] stack.append(6) stack.append(7) stack [3, 4, 5, 6, 7] stack.pop() #删除最后一个对象 7 stack [3, 4, 5, 6] stack.pop() 6 stack.pop() 5 stack [3, 4]
##use a list as a queue: #Use a list like a queue
> from collections import deque #这里需要使用模块deque > queue = deque(["Eric", "John", "Michael"]) > queue.append("Terry") # Terry arrives > queue.append("Graham") # Graham arrives > queue.popleft() # The first to arrive now leaves 'Eric' > queue.popleft() # The second to arrive now leaves 'John' > queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])
Three built-in functions: Three important built-in functions
filter(), map(), and reduce(). 1), filter(function, sequence)::
According to the function function Rules filter data in the list sequence
> def f(x): return x % 3 == 0 or x % 5 == 0 ... #f函数为定义整数对象x,x性质为是3或5的倍数 > filter(f, range(2, 25)) #筛选 [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]2), map(function, sequence):
The map function implements the list sequence according to the rules of the function function Do the same processing,
The sequence here is not limited to lists, tuples can also be used.
> def cube(x): return x*x*x #这里是立方计算 还可以使用 x**3的方法 ... > map(cube, range(1, 11)) #对列表的每个对象进行立方计算 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]Note: The parameter list here is not fixed. It mainly depends on the number of parameters of the custom function. The map function can be transformed into: def func( x,y) map(func, sequence1, sequence2) Example:
seq = range(8) #定义一个列表 > def add(x, y): return x+y #自定义函数,有两个形参 ... > map(add, seq, seq) #使用map函数,后两个参数为函数add对应的操作数,如果列表长度不一致会出现错误 [0, 2, 4, 6, 8, 10, 12, 14]3), reduce(function, sequence):
reduce function function is Operate the data in the sequence according to the function function, such as performing a function operation on the first number and the second number in the list, and perform a function operation on the result and the next data in the list, and the loop continues...
Example:
def add(x,y): return x+y ... reduce(add, range(1, 11)) 55
List comprehensions:
Here we will introduce several applications of lists:
squares = [ x**2 for x in range(10)]
#Generate a list. The list is the result of square calculation of the list generated by the list range(10).
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
#[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] Here is a list generated , each item of the list is a tuple, each tuple is composed of x and y, x is provided by the list [1,2,3], y comes from [3,1,4], and satisfies the rule x! =y.
Nested List Comprehensions:
It’s difficult to translate here, so let’s give an example:
matrix = [ #此处定义一个矩阵 ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ] [[row[i] for row in matrix] for i in range(4)] #[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]Here Two levels of nesting is troublesome. Let me explain briefly: For the matrix matrix, for row in matrix is used to extract each row of the matrix. row[i] is used to extract the i-th (subscript) in the list of each row, generate a list, and then i again comes from for i in range(4), which generates a list of lists.
The del statement: Delete the specified data in the list, for example:
> a = [-1, 1, 66.25, 333, 333, 1234.5] >del a[0] #删除下标为0的元素 >a [1, 66.25, 333, 333, 1234.5] >del a[2:4] #从列表中删除下标为2,3的元素 >a [1, 66.25, 1234.5] >del a[:] #全部删除 效果同 del a >a []
Sets: Collection
> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> fruit = set(basket) # create a set without duplicates >>> fruit set(['orange', 'pear', 'apple', 'banana']) >>> 'orange' in fruit # fast membership testing True >>> 'crabgrass' in fruit False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a set(['a', 'r', 'b', 'c', 'd']) >>> a - b # letters in a but not in b set(['r', 'd', 'b']) >>> a | b # letters in either a or b set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l']) >>> a & b # letters in both a and b set(['a', 'c']) >>> a ^ b # letters in a or b but not both set(['r', 'd', 'b', 'm', 'z', 'l'])
Dictionaries: Dictionaries
>>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 #相当于向字典中添加数据 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098} >>> tel['jack'] #取数据 4098 >>> del tel['sape'] #删除数据 >>> tel['irv'] = 4127 #修改数据 >>> tel {'guido': 4127, 'irv': 4127, 'jack': 4098} >>> tel.keys() #取字典的所有key值 ['guido', 'irv', 'jack'] >>> 'guido' in tel #判断元素的key是否在字典中 True >>> tel.get('irv') #取数据 4127You can also use rules to generate a dictionary:
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36}
enumerate(): Traverse elements and subscriptsenumerate function is used to traverse The elements in the sequence and their subscripts:
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print i, v ... 0 tic 1 tac 2 toe
zip():
zip() is an inner function of Python Create a function that accepts a series of iterable objects as parameters, packs the corresponding elements in the objects into tuples, and then returns a list composed of these tuples. If the lengths of the parameters passed in are not equal, the length of the returned list will be the same as the object with the shortest length among the parameters. Using the * operator, you can unzip (decompress) the list.
>>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print 'What is your {0}? It is {1}.'.format(q, a) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue.Give a simple example about zip:
>>> a = [1,2,3] >>> b = [4,5,6] >>> c = [4,5,6,7,8] >>> zipped = zip(a,b) [(1, 4), (2, 5), (3, 6)] >>> zip(a,c) [(1, 4), (2, 5), (3, 6)] >>> zip(*zipped) [(1, 2, 3), (4, 5, 6)]
reversed(): reverse
>>> for i in reversed(xrange(1,10,2)): ... print i ...
sorted(): sort
> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] > for f in sorted(set(basket)): #这里使用了set函数 ... print f ... apple banana orange pearPython's set is similar to other languages. It is a basic function including relationship testing and eliminating duplicate elements.
To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
>>> words = ['cat', 'window', 'defenestrate'] >>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate']The above is the entire content of this article, I hope it will be helpful to everyone's study. For more articles related to list advanced functions in Python, please pay attention to the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use
