Home Backend Development Python Tutorial python中list列表的高级函数

python中list列表的高级函数

Jun 10, 2016 pm 03:04 PM
list python list

在Python所有的数据结构中,list具有重要地位,并且非常的方便,这篇文章主要是讲解list列表的高级应用,基础知识可以查看博客。
此文章为python英文文档的翻译版本,你也可以查看英文版:https://docs.python.org/2/tutorial/datastructures.html

use a list as 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]
Copy after login

use a list as 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'])

Copy after login

three built-in functions: 三个重要的内建函数

filter(), map(), and reduce().
1)、filter(function, sequence)::
按照function函数的规则在列表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]

Copy after login

2)、map(function, sequence):
map函数实现按照function函数的规则对列表sequence做同样的处理,
这里sequence不局限于列表,元组同样也可。

> def cube(x): return x*x*x #这里是立方计算 还可以使用 x**3的方法
...
> map(cube, range(1, 11)) #对列表的每个对象进行立方计算
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Copy after login

注意:这里的参数列表不是固定不变的,主要看自定义函数的参数个数,map函数可以变形为:def func(x,y) map(func,sequence1,sequence2) 举例:

 seq = range(8)  #定义一个列表
> def add(x, y): return x+y #自定义函数,有两个形参
...
> map(add, seq, seq) #使用map函数,后两个参数为函数add对应的操作数,如果列表长度不一致会出现错误
[0, 2, 4, 6, 8, 10, 12, 14]
Copy after login

3)、reduce(function, sequence):
reduce函数功能是将sequence中数据,按照function函数操作,如 将列表第一个数与第二个数进行function操作,得到的结果和列表中下一个数据进行function操作,一直循环下去…
举例:

def add(x,y): return x+y
...
reduce(add, range(1, 11))
55

Copy after login

List comprehensions:
这里将介绍列表的几个应用:
squares = [x**2 for x in range(10)]
#生成一个列表,列表是由列表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)] 这里是生成了一个列表,列表的每一项为元组,每个元组是由x和y组成,x是由列表[1,2,3]提供,y来源于[3,1,4],并且满足法则x!=y。

Nested List Comprehensions:
这里比较难翻译,就举例说明一下吧:

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

Copy after login

这里两层嵌套比较麻烦,简单讲解一下:对矩阵matrix,for row in matrix来取出矩阵的每一行,row[i]为取出每行列表中的第i个(下标),生成一个列表,然后i又是来源于for i in range(4) 这样就生成了一个列表的列表。

The del statement:
删除列表指定数据,举例:

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

Copy after login

Sets: 集合

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

Copy after login

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') #取数据
4127

Copy after login

也可以使用规则生成字典:

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
Copy after login

enumerate():遍历元素及下标
enumerate 函数用于遍历序列中的元素以及它们的下标:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...   print i, v
...
0 tic
1 tac
2 toe
Copy after login

zip():
zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同。利用*号操作符,可以将list unzip(解压)。

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

Copy after login

有关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)]
Copy after login

reversed():反转

>>> for i in reversed(xrange(1,10,2)):
...   print i
...

Copy after login

sorted(): 排序

> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
> for f in sorted(set(basket)):       #这里使用了set函数
...   print f
...
apple
banana
orange
pear
Copy after login

python的set和其他语言类似, 是一个 基本功能包括关系测试和消除重复元素.

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']
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is there any mobile app that can convert XML into PDF? Is there any mobile app that can convert XML into PDF? Apr 02, 2025 pm 08:54 PM

An application that converts XML directly to PDF cannot be found because they are two fundamentally different formats. XML is used to store data, while PDF is used to display documents. To complete the transformation, you can use programming languages ​​and libraries such as Python and ReportLab to parse XML data and generate PDF documents.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

What is the process of converting XML into images? What is the process of converting XML into images? Apr 02, 2025 pm 08:24 PM

To convert XML images, you need to determine the XML data structure first, then select a suitable graphical library (such as Python's matplotlib) and method, select a visualization strategy based on the data structure, consider the data volume and image format, perform batch processing or use efficient libraries, and finally save it as PNG, JPEG, or SVG according to the needs.

Is there a mobile app that can convert XML into PDF? Is there a mobile app that can convert XML into PDF? Apr 02, 2025 pm 09:45 PM

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

See all articles