参考链接: Python清单

python 需求清单

列出功能和方法,理解和性能特征 (List Functions & Methods, Comprehension and Performance Characteristics)

The list is the common multipurpose data type available in Python 3, which can be listed as a list of comma-marked values(items) within square bracket. The items in a list need not be the same type and it is the important thing about a list.

该列表是Python 3中可用的通用多用途数据类型,可以作为方括号内的逗号标记值(项目)列表列出。 列表中的项目不必是同一类型,这对于列表来说很重要。

访问列表中的值 (Accessing Values in Lists)

To enter values in list, apply the square brackets for slicing along with the index or indices to get value available at that index

要在列表中输入值,请将方括号与一个或多个索引一起切​​片,以获取该索引处的可用值

list1 = ['Monday','Tuesday','10','11']list2 = [8,9,10,15]list3 = ["j","i","t"]list1[0]list2[1:3]OutputMonday[9, 10]

更新清单 (Updating Lists)

By using the slice on the left-hand side of the assignment operator we can update single or multiple elements of list. We can also add a element in the list by using append() method.

通过使用赋值运算符左侧的切片,我们可以更新列表的单个或多个元素。 我们还可以使用append()方法在列表中添加一个元素。

list1 = ['Monday','Tuesday','10','11']list1[2]list1[2] = 500list1Output10['Monday', 'Tuesday', 500, '11']

删除列表元素 (Delete List Elements)

We can delete a element in a list using the del if we know the element. We can also use the remove() method if we dont know the position.del can also be used to delete entire variables.

如果我们知道元素,可以使用del删除列表中的元素。 如果我们不知道位置,我们也可以使用remove()方法。 del也可以用于删除整个变量。

list1 = ['Monday','Tuesday','10','11']del list1[3]list1Output['Monday', 'Tuesday', '10']

基本列表操作 (Basic List Operations)

Just like the strings, we can also add and multiply using + and * operators. The output is a new list and not a string

就像字符串一样,我们也可以使用+和*运算符进行加法和乘法运算。 输出是一个新列表,而不是字符串

------------------------------Lengthlen([1,2,3,])Output3------------------------------Concatenation[1,2,3]+[4,5,6]Output[1,2,3,4,5,6]------------------------------Repetition['Hi!']*4Output['Hi!', 'Hi!', 'Hi!', 'Hi!']------------------------------Membership3 in [1,2,3]OutputTrue------------------------------Iterationfor a in [1,2,3]: print(a,end='')Output123

索引,切片 (Indexing, Slicing)

Indexing and slicing works the same way for lists as they do for strings because lists are sequences

列表的索引和切片与字符串的工作方式相同,因为列表是序列

list = ["Mango", 'Apple', 'Banana']list[2]     //Offset starts at 0list[-2]    //Negative: count from the rightlist[1:]    //Slicing fetches selectionOutput'Banana''Apple'['Apple','Banana']

内置列表功能和方法 (Built in List functions and Methods)

清单功能 (List Functions)

Python List functions

Python列表功能

清单长度 (Length of a List)

The len(list) function gives the length of a list.

len(list)函数给出len(list)的长度。

list = ["Mango", 'Apple', 'Banana']len(list)Output3

列表中的最大值 (Max Value in a list)

The max(list) function gives the maximum value in a list.

max(list)函数给出max(list)的最大值。

list = [1,2,3,4,5,6]max(list)Output6

列表中的最小值 (Min Value in a list)

The min(list) function gives the minimum value in a list.

min(list)函数给出min(list)的最小值。

list = [1,2,3,4,5,6]min(list)Output1

将元组转换为列表 (Convert tuple to list)

The list(seq) function can be used to convert a tuple to list.

list(seq)函数可用于将元组转换为list。

tup1 = (1,2,3,4,5)type(tup1)tup1list(tup1)Output<class 'tuple'>(1, 2, 3, 4, 5)[1,2,3,4,5]

清单方法 (List Methods)

Python List methods

Python List方法

附加 (Append)

The list.append(obj) method is used to append the object to listEquivalent to a[len(a):] = [x]

list.append(obj)方法用于将对象追加到list a[len(a):] = [x] e]等效于a[len(a):] = [x]

list1 = [1,2,3,4,5,6]list1.append(7)list1Output[1, 2, 3, 4, 5, 6, 7]

计数 (Count)

The list.count(obj) method is used to count the number of object in the list

list.count(obj)方法用于计算列表中对象的数量

list1 = [1,2,3,4,5,6,2]list1.count(2)Output2

将序列附加到列表 (Attach Sequence to list)

The list.extend(seq) method is used to append the contents of sequence to list. Equivalent to a[len(a):] = iterable

list.extend(seq)方法用于将序列的内容追加到list。 等效于a[len(a):] = iterable

list1 = [1,2,3]list1.extend([4,5,6])Output[1, 2, 3, 4, 5, 6]

对象索引 (Index of the Object)

The list.index(obj) returns the lowest index in the list.

list.index(obj)返回列表中的最低索引。

list1 = [1,2,3]list1.index(2)Output1

插入物件 (Insert a Object)

The list.insert(index, obj) inserts object obj into list at offset index.#1 a.insert(0, x) — Insert at front of the list#2 a.insert(len(a), x) —Insert at the end is equivalent to a.append(x)

list.insert(index, obj)将对象obj插入偏移量为index的列表中。#1 a.insert(0, x) -插入列表的最前面  #2 a.insert(len(a), x)最后插入等效于a.append(x)

list1 = [1,2,3]list1.index(2,4)Output[1, 2, '4', 3]

排序清单 (Sort a list)

The list.sort(key=None, reverse=False) is used to sort the items of the list in place.

list.sort( key=None , reverse=False )用于对列表中的项目进行排序。

list1 = [2,1,5,0]list1.sort()Output[0, 1, 2, 5]

删除最后一个值 (Remove last value)

The list.pop(obj=list[-1]) removes and returns the last object or obj from list.

list.pop(obj=list[-1])从列表中删除并返回最后一个对象或obj。

list1 = [1,2,3,4,5]list1.pop()list1.pop(0)Output51

复制清单 (Copy a list)

The list.copy() is used to return a shallow copy of the list. Equivalent to a[:]

list.copy()用于返回列表的浅表副本。 相当于a[:]

list1 = [1,2,3,4,5]list1.copy()Output[1, 2, 3, 4, 5]

明确 (Clear)

The list.clear() is used to remove all objects from the list. Equivalent to del a[:]

list.clear()用于从列表中删除所有对象。 等效于del a[:]

list1 = [1,2,3,4,5]list1.clear()Output[]

去掉 (Remove)

The list.remove(obj) removes the first object from the list.

list.remove(obj)从列表中删除第一个对象。

list1 = [1,2,3,4,5]list1.remove(2)list1Output[1, 3, 4, 5]

逆转 (Reverse)

The list.reverse() is used to reverse the objects of list in place.

list.reverse()用于在适当位置反转list的对象。

list1 = [1,2,3,4,5]list1.reverse()list1Output[5, 4, 3, 2, 1]

将列表用作队列 (Using Lists as Queues)

It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).

也可以使用列表作为队列,其中添加的第一个元素是检索到的第一个元素(“先进先出”); 但是,列表对于此目的并不有效。 尽管从列表末尾开始的添加和弹出很快速,但是从列表开头进行插入或弹出是很慢的(因为所有其他元素都必须移位一个)。

from collections import dequequeue = deque(["Apple", "Mango", "Banana"])queue.append("Grapes")         # Grapes is appendedqueue.append("Orange")         # Orange is appendedqueue.popleft()                # The first to arrive now leaves'Apple'queue.popleft()                # The second to arrive now leaves'Mango'queue                          # Remaining queue in order of arrivaldeque(['Banana', 'Grapes', 'Orange'])

使用列表作为堆栈 (Using Lists as Stacks)

The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index.

使用list 方法可以很容易地将列表用作堆栈,其中最后添加的元素是检索到的第一个元素(“后进先出”)。 要将项目添加到堆栈的顶部,请使用append() 。 要从堆栈顶部检索项目,请使用没有显式索引的pop() 。

stack = [3, 4, 5]stack.append(6)stack.append(7)stack[3, 4, 5, 6, 7]stack.pop()7stack[3, 4, 5, 6]stack.pop()6stack.pop()5stack[3, 4]

清单理解 (List Comprehensions)

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

列表理解为创建列表提供了一种简洁的方法。 常见的应用是创建新列表,其中每个元素是应用于另一个序列的每个成员或可迭代的某些操作的结果,或者创建满足特定条件的那些元素的子序列。

Example: Creating a List of Squares.

示例:创建正方形列表。

-----------------------------------------------Method 1:Program-----------------------------------------------squares = []for x in range(10):...     squares.append(x**2)...squaresOutput[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]-----------------------------------------------Method 2: Using Map and lamda functions-----------------------------------------------squares = list(map(lambda x: x**2, range(10)))squaresOutput[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]-----------------------------------------------Method 3:List Comprehension-----------------------------------------------squares = [x**2 for x in range(10)]squaresOutput[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]-----------------------------------------------

Below are some of the List Comprehension.

以下是一些列表理解 。

-----------------------------------------------# create a new list with the values doubleda = [1,2,3,-4][x*2 for x in a]Output[2, 4, 6, -8]-----------------------------------------------# filter the list to exclude negative numbers[x for x in a if x >= 0]Output[1, 2, 3]-----------------------------------------------# apply a function to all the elements[abs(x) for x in a]Output[1, 2, 3, 4]-----------------------------------------------# call a method on each elementDays = ['      Sunday', 'Monday     ', 'Tuesday'][blank.strip() for blank in Days]Output['Sunday', 'Monday', 'Tuesday']-----------------------------------------------# create a list of 2-tuples like (number, square)[(x, x**2) for x in range(6)]Output[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]-----------------------------------------------# flatten a list using a listcomp with two 'for'a = [[1,2,3], [4,5,6], [7,8,9]][num for elem in a for num in elem]Output[1, 2, 3, 4, 5, 6, 7, 8, 9]-----------------------------------------------#Extract vowels from sentencesentence = 'the is a sample sentence'vowels = [i for i in sentence if i in 'aeiou']vowelsOutput['e', 'i', 'a', 'a', 'e', 'e', 'e', 'e']-----------------------------------------------#Show the first letter of each wordWords = ["this","is","a","list","of","words"]items = [ word[0] for word in Words ]print(items)Output['t', 'i', 'a', 'l', 'o', 'w']-----------------------------------------------#Lower/Upper case converter[x.lower() for x in ["A","B","C"]][x.upper() for x in ["a","b","c"]]Output['a', 'b', 'c']['A', 'B', 'C']-----------------------------------------------#Print numbers only from stringstring = "Hello 12345 World"numbers = [x for x in string if x.isdigit()]print numbersOutput['1', '2', '3', '4', '5']-----------------------------------------------#Parsing a file using list comprehensionfh = open("test.txt", "r")result = [i for i in fh if "line3" in i]print resultOutputthis is line3-----------------------------------------------#Find matching elements in two listlist1 = [1,2,3,4,5,6,6,5]list2 = [3, 5, 7, 9]list(set(list1).intersection(list2))Output[3, 5]-----------------------------------------------# Compound Listslist_one = list_two = list_three = -----------------------------------------------# Print Odd numbers from the listlist1 = [1,2,3,4,5,6,7,8,9,10]print(list1)new_list = [ x for x in list1 if x%2 ]print(new_list)Output[1, 2, 3, 4, 5, 6, 7, 8, 9, 10][1, 3, 5, 7, 9]-----------------------------------------------# Print multiplication tabletable = [[x*y for y in range(1,11)] for x in range(4,7)]print(table)Output[[4, 8, 12, 16, 20, 24, 28, 32, 36, 40], [5, 10, 15, 20, 25, 30, 35, 40, 45, 50], [6, 12, 18, 24, 30, 36, 42, 48, 54, 60]]-----------------------------------------------# Finding Primesnoprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]primes = [x for x in range(2, 50) if x not in noprimes]Output[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]-----------------------------------------------# Get a list of txt files in a directoryimport osfiles = [f for f in os.listdir('./my_dir') if f.endswith('.txt')]#Get a list of the relative pathsimport osfiles = [os.path.join('./my_dir', f) for f in os.listdir('./my_dir') if f.endswith('.txt')]-----------------------------------------------#Read a csv into a listed dictionaryimport csvdata = [ x for x in csv.DictReader(open('file.csv', 'rU'))]-----------------------------------------------

嵌套列表推导 (Nested List Comprehensions)

The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.

列表推导中的初始表达式可以是任意表达式,包括另一个列表推导。

# Transposing a 3*3 Matrixmatrix = [...     [1, 2, 3, 4],...     [5, 6, 7, 8],...     [9, 10, 11, 12],... ][[row[i] for row in matrix] for i in range(4)]list(zip(*matrix))                         //Using Built in functionOutput[[1, 3, 6], [2, 4, 7], [3, 5, 8]][[1, 3, 6], [2, 4, 7], [3, 5, 8]]

最后的想法 (Final Thoughts)

The list has the following performance characteristics. The below performance characteristics was taken from here.

该列表具有以下性能特征。 以下性能特征是从此处得出的。

The list object stores pointers to objects, not the actual objects, memory used depends on the number of objects in the list and not the size of the objects itself. 列表对象存储指向对象(而不是实际对象)的指针,所使用的内存取决于列表中对象的数量,而不是对象本身的大小。 The time needed to get or set an individual item is constant, no matter what the size of the list is (also known as “O(1)” behaviour). 无论列表的大小如何,获取或设置单个项目所需的时间都是恒定的(也称为“ O(1)”行为)。 The time needed to append an item to the list is “amortized constant”; whenever the list needs to allocate more memory, it allocates room for a few items more than it actually needs, to avoid having to reallocate on each call (this assumes that the memory allocator is fast; for huge lists, the allocation overhead may push the behaviour towards O(n*n)). 将项目追加到列表所需的时间为“摊余常数”; 每当列表需要分配更多的内存时,它就会为超出实际需要的空间分配更多的空间,以避免每次调用都需要重新分配(这假定内存分配器是快速的;对于大型列表,分配开销可能会增加对O(n * n)的行为)。 The time needed to insert an item depends on the size of the list, or more exactly, how many items that are to the right of the inserted item (O(n)). In other words, inserting items at the end is fast, but inserting items at the beginning can be relatively slow, if the list is large. 插入项目所需的时间取决于列表的大小,或更确切地说,取决于插入的项目(O(n))右边的项目数。 换句话说,如果列表很大,则在末尾插入项目很快,但是在开始处插入项目可能相对较慢。 The time needed to remove an item is about the same as the time needed to insert an item at the same location; removing items at the end is fast, removing items at the beginning is slow. 删除项目所需的时间与在同一位置插入项目所需的时间大约相同。 在结尾处删除项目很快,而在开头处删除项目很慢。 The time needed to reverse a list is proportional to the list size (O(n)). 反转列表所需的时间与列表大小(O(n))成正比。 The time needed to sort a list varies; the worst case is O(n log n), but typical cases are often a lot better than that. 排序列表所需的时间各不相同; 最坏的情况是O(n log n),但典型情况通常要好得多。

翻译自: https://medium.com/python-in-plain-english/python-list-operation-summary-262f40a863c8

python 需求清单

[转载] python 需求清单_Python清单操作摘要相关推荐

  1. python 技能清单_Python清单

    python 技能清单 Today we going to learn about Python List. Earlier we learnt about Python Numbers which ...

  2. python的数据库_python数据库操作-mysql数据库

    一:连接 1:本地连接 mysql -u用户名 -p密码 2:连接远程服务器 mysql -u用户名 -p密码 -hip地址 -P端口号 线下修改远程服务端上部署的mysql服务器 二:创建数据库 c ...

  3. python目录遍历_python文件操作之目录遍历实例分析

    本文实例讲述了python文件操作之目录遍历的方法.分享给大家供大家参考.具体分析如下: Python的os模块,包含了普遍的操作系统功能,这里主要学习与路径相关的函数: os.listdir(dir ...

  4. python sorted下标_Python列表操作最全面总结

    1.列表添加元素 列表中可以使用append.insert.extend方法实现元素的添加. append会把新元素添加到列表末尾 "a", insert(index, objec ...

  5. python 文件函数_python文件操作及函数学习

    文件操作 文件读 f = open('a.txt', encoding='utf-8', mode='r')  #只读方式打开文件 data = f.read()  #read函数读取所有文件内容,光 ...

  6. python open写入_Python IO操作文件读取和写入、open函数的mode参数、buffering,文件缓冲区...

    IO编程 文件读写 打开文件 open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closef ...

  7. [转载] python仿真入门_python基础-入门

    参考链接: Pytho 集合set symmetric_difference() 主要包括: 1.变量 2.用户输入 3.if...else语句 4.for循环 5.while循环 6.break和c ...

  8. [转载] python 字典查找_python字典的增,删,改,查

    参考链接: Python字典clear() 字典---dict 1.字典是无序,可变的数据类型 2.字典:用于存储数据,存储大量数据,字典要比列表快,将数据和数据之间进行关联 定义一个字典: dic ...

  9. [转载] python定义整型常量_Python笔记——数据类型、变量和常量

    参考链接: Python变量,常量和文字 数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频 ...

最新文章

  1. 1.NetDh框架之数据库操作层--Dapper简单封装,可支持多库实例、多种数据库类型等(附源码和示例代码)...
  2. IOS开发之----异常处理
  3. java accessablity_java连接access数据库----简单demo
  4. JS原生封装时间函数 日期格式过滤
  5. 团队作业4——第一次项目冲刺(Alpha版本)第三天
  6. 特斯拉CEO马斯克又怼巴菲特:别把冰雪皇后给毁了
  7. c语言计算日期天数,关于计算两个日期间天数的代码,大家来看看
  8. 服务端设置忽略更新_深入理解Kafka服务端之日志对象的读写数据流程
  9. 联想Lenovo拯救者 Legion R9000P 2021H 触控板失灵
  10. leetcode807. 保持城市天际线(java)
  11. Matlab中的数值精度问题
  12. Repository “http://xxx@git.xxx.net/xxx/xxx.git”not found 解决
  13. 2013计算机学科排名,2013年美国大学排名计算机专业排名情况
  14. CCNP课堂练习一:详解交换机vlan的介绍及通过交换机从逻辑上划分区域配置
  15. web linux 桌面,Ubuntu无桌面进行Web浏览器测试
  16. 零基础小白必看----2020年最新Java学习路线图(纯干货)
  17. 盖茨基金会宣布再追加捐赠1.5亿美元,支持全球新冠肺炎响应行动
  18. 【学习总结】激光雷达与相机外参标定:原理与代码1
  19. editable string 转_常见问题 | x-editable 中文网
  20. FFMPEG视音频编解码学习(一)

热门文章

  1. 电脑怎么进入linux系统,Linux操作系统进入家用电脑成为发展新前景
  2. Windows批处理BAT脚本
  3. termux使用无图形界面linux,在termux上使用图形化
  4. 青岛理工大学c语言软件,青岛理工大学C语言程序打印版.docx
  5. JavaScript事件与处理程序绑定(1)
  6. sublime后缀_在sublime text中如何设置某种扩展名文件的默认语法
  7. CSS选择器的优先级计算
  8. 保存最大的前20项暴力--Heritage of skywalkert
  9. yolov3识别的类别_Gaussian YOLOv3:一个更强的YOLOv3,现已开源!
  10. 取文字_玉镯取不出来了怎么办?教你6种最有效的方法