[转载] python 需求清单_Python清单操作摘要

参考链接: 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 需求清单

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值