python map循环
The major advantage of using computer programs to solve a problem is that we have more than one way to solve a particular problem. The process of finding the best logical solution among others makes the programmer unique. Concept of iteration is an important methodology in programming which serves great support to reduce the code complexity.
使用计算机程序解决问题的主要优点是,我们有多种解决特定问题的方法。 寻找最佳逻辑解决方案的过程使程序员与众不同。 迭代的概念是编程中的一种重要方法,为降低代码复杂性提供了强有力的支持。
In one of my previous article, a reader asked me a question. Which one is best among the list comprehension and map function? After doing further research on those topics, I found some useful information about the topic.
在上一篇文章中,一位读者问我一个问题。 列表理解和地图功能中哪一个最好? 在对这些主题进行了进一步研究之后,我发现了一些有关该主题的有用信息。
While taking this kind of performance tests, we may wonder what will go wrong if our program takes extra data and time. If you are a beginner or an expert in any field of information technology, always remember, each byte counts. We don’t need a better solution. We have to find the best solution.
在进行这种性能测试时,我们可能想知道如果我们的程序花费额外的数据和时间会出什么问题。 如果您是信息技术任何领域的初学者或专家,请始终记住,每个字节都很重要。 我们不需要更好的解决方案。 我们必须找到最佳解决方案。
A single byte of data or time you are saving in your program will make an huge impact on the entire data network. So to be a good developer, do not compromise with the complexities.
您在程序中保存的单个数据字节或时间将对整个数据网络产生巨大影响。 因此,要成为一名优秀的开发人员,不要在复杂性上妥协。
In this article, we are going to analyze the three different strategies that are mentioned in the title in more pythonic way. First things first. We are going to analyze the time complexities of python codes producing same results. Lets get started!
在本文中,我们将以更Python化的方式分析标题中提到的三种不同策略。 首先是第一件事。 我们将分析产生相同结果的python代码的时间复杂度。 让我们开始吧!
Computer programming is simply a process of redesigning the real world in computers. While designing computer program we may come across repetition of same kind of task for multiple times.
计算机编程只是重新设计计算机现实世界的过程。 在设计计算机程序时,我们可能多次遇到相同任务的重复。
The concepts such as looping eliminates the repeating instruction by simply defining the iteration range. Creating loops is a basic step in iteration concept which helps the programmer to write repeating tasks.
循环之类的概念通过简单地定义迭代范围来消除重复指令。 创建循环是迭代概念中的基本步骤,可帮助程序员编写重复的任务。
Complete beginners can take a look at the following definitions and implementations of python programs using different iterating concepts such as loop, list comprehension and map. Those who are already aware of the concepts can skip this part.
完整的初学者可以使用不同的迭代概念(例如循环,列表理解和映射)了解以下python程序的定义和实现。 那些已经意识到这些概念的人可以跳过这一部分。
Loops are objects in python which iterates over the iterable objects such as string, list and range functions. There are two types of loops are available in python. The types are for and while. The for loop iterates over the iterable elements whereas the while loop iterates when a condition is True.
循环是python中的对象,它遍历可迭代对象,例如字符串,列表和范围函数。 在python中有两种可用的循环类型。 类型是for和while 。 for循环在可迭代元素上迭代,而while循环在条件为True时迭代。
Image From Author’s Desktop 图片来自作者的桌面The for loop
for循环
The for loop is used to iterate over a sequence of characters. We can use list, sets, tuples, dictionary and string. The syntax for using the for loop is given below.
for循环用于遍历一系列字符。 我们可以使用列表,集合,元组,字典和字符串。 下面给出了使用for循环的语法。
Syntax: for var_name in iterable_obj:
语法:在iterable_obj VAR_NAME:
The statements that must be repeated multiple times are written inside the indented block under the for loop statement. The following program contains various iterable objects and for loops created using the iterables.
必须重复多次的语句写在for循环语句下的缩进块中。 以下程序包含各种可迭代对象以及使用可迭代对象创建的循环。
string = 'WFH'mylist = [1, 2, 3, 4, 5]tuplex = (1, 2, 3, 4, 5)my_set = {1, 2, 3, 4, 5}mydict = {'A':1, 'B':2, 'C':3}for var_c in string: print(var_c, end=' ')print('')for var_l in mylist: print(var_l, end=' ')print('')for var_t in tuplex: print(var_t, end=' ')print('')for var_s in my_set: print(var_s, end=' ')print('')for var_d in mydict: print(var_d, end=' ')print('')for var_y in range(5): print(var_y, end=' ')Output
输出量
W F H1 2 3 4 51 2 3 4 51 2 3 4 5B A C0 1 2 3 4The while loop
while循环
The while loop is used for creating loops with conditional statements. The syntax for using while loop is given here.
while循环用于使用条件语句创建循环。 这里给出了使用while循环的语法。
Syntax: while condition:
语法: while条件:
a = 5while a>0: print(a, end=' ') a = a-1Output
输出量
5 4 3 2 1The list comprehension is an one liner for creating list objects in elegant way. Using list comprehension in python simplifies the code complexibility. The list comprehension can be created using following syntax.
列表理解是一种以优雅的方式创建列表对象的方法。 在python中使用列表理解可以简化代码的复杂性。 列表理解可以使用以下语法创建。
Syntax: list_obj = [expression for item in iterable]
语法:list_obj = [在迭代项表达式]
list_obj = [x for x in range(8)]print(list_obj)Output
输出量
[0, 1, 2, 3, 4, 5, 6, 7]Map object helps us to run a function for every iterable in a sequence. It takes two arguments function and iterable objects.
Map对象帮助我们为序列中的每个可迭代对象运行一个函数。 它需要两个参数函数和可迭代对象。
Syntax: map(function, iterable)
语法:map(函数,可迭代)
def add(n): return n + 2 numbers = [1, 2, 3, 4, 5]value = map(add, numbers) print(list(value))Output
输出量
[3, 4, 5, 6, 7]In this step we will analyse the time taken for each process of ieterating. The major objective of the program is to create a list of numbers. Here the logical programs to create the list [0, 1, 2, 3, 4] in Python.
在这一步中,我们将分析每个隔离过程所花费的时间。 该程序的主要目的是创建一个数字列表。 这里的逻辑程序在Python中创建列表[0,1,2,3,4]。
These are the code snippets written for creating a list. We can use this template to find the execution time of each kind of loops.
这些是用于创建列表的代码段。 我们可以使用该模板来查找每种循环的执行时间。
To calculate the time of execuion we may use the time module. To use the methods in the module, we have to import the module usn import keyword.
为了计算执行时间,我们可以使用时间模块。 要使用模块中的方法,我们必须使用usn import关键字导入模块。
The optimized version of previous code examples are given here. Be clear at which position we are calculating start and end time.
此处提供了先前代码示例的优化版本。 请清楚我们要计算开始和结束时间的位置。
Output
输出量
1.0046305656433105Output
输出量
1.001749038696289Output
输出量
1.0046463012695312In the previous section we have used the concepts for list with 5 elements. Let us try to run each methods for 1 to 1000 elements using for loop. In the code each time a master_list will be created. That master list will be used for execution time calculation. Also we need to store the values in separate lists.
在上一节中,我们使用了包含5个元素的list的概念。 让我们尝试使用for循环为1到1000个元素运行每种方法。 每次都会在代码中创建一个master_list。 该主列表将用于执行时间计算。 另外,我们需要将值存储在单独的列表中。
The steps to develop such program is given below.
下面给出了开发此类程序的步骤。
Step 1 - Getting the value of n from the user. (Let n=20 for now).
步骤1-从用户处获取n的值。 (现在让n = 20)。
Step 2 - Creating a list contains the numbers from 1 to n(input_list).
步骤2-创建一个列表,其中包含从1到n(input_list)的数字。
Step 3 - Creating three empty lists time_for_loop, time_list_comp, time_map_fun
第3步-创建三个空列表time_for_loop,time_list_comp,time_map_fun
Step 4 - Passing each value of input_list through the for loop.
第4步-通过for循环传递input_list的每个值。
Step 5 - Creating master list each time.
第5步-每次创建主列表。
Step 6 - Calculating time taken for each method of iterations.
步骤6-计算每种迭代方法所花费的时间。
import timedef func(x): return xdef func_for(item): resultant_list = [] start_time = time.time()for m in item: resultant_list.append(m) time.sleep(1) end_time = time.time()return end_time - start_timedef func_list(item): start_time = time.time()resultant_list = [m for m in item] time.sleep(1) end_time = time.time()return end_time - start_timedef func_map(item): start_time = time.time()resultant_object = map(func, master_list) time.sleep(1) resultant_list = list(resultant_object) end_time = time.time()return end_time - start_timetime_for_loop = []time_list_comp = []time_map_fun = []n = int(input("Enter a Limit:"))for x in range(1,n): master_list = [a for a in range(x)] print(master_list) time_for_loop.append( func_for( master_list ) ) time_list_comp.append( func_list( master_list ) ) time_map_fun.append( func_map( master_list ) )print( time_for_loop )print( time_list_comp )print( time_map_fun )Output
输出量
Enter a Limit:20[0][0, 1][0, 1, 2][0, 1, 2, 3][0, 1, 2, 3, 4][0, 1, 2, 3, 4, 5][0, 1, 2, 3, 4, 5, 6][0, 1, 2, 3, 4, 5, 6, 7][0, 1, 2, 3, 4, 5, 6, 7, 8][0, 1, 2, 3, 4, 5, 6, 7, 8, 9][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17][0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18][1.002516508102417, 1.00276780128479, 1.011702537536621, 1.000199794769287, 1.0024888515472412, 1.0024185180664062, 1.0026524066925049, 1.0007808208465576, 1.0017104148864746, 1.0036208629608154, 1.0001416206359863, 1.0023691654205322, 1.0033345222473145, 1.0044755935668945, 1.0000123977661133, 1.0039172172546387, 1.0001366138458252, 1.002025842666626, 1.0012400150299072][1.0002338886260986, 1.004652976989746, 1.0002458095550537, 1.0049526691436768, 1.0002472400665283, 1.0008893013000488, 1.0039539337158203, 1.0029950141906738, 1.0004897117614746, 1.000626802444458, 1.0043294429779053, 1.001443862915039, 1.003732442855835, 1.0021586418151855, 1.0000550746917725, 1.0033528804779053, 1.0023748874664307, 1.004514455795288, 1.0006587505340576][1.0041062831878662, 1.003089427947998, 1.001046895980835, 1.0021331310272217, 1.000084400177002, 1.0042176246643066, 1.0026190280914307, 1.003239631652832, 1.004948616027832, 1.0041661262512207, 1.0045571327209473, 1.000291347503662, 1.0014476776123047, 1.003342628479004, 1.0027976036071777, 1.002122163772583, 1.0021615028381348, 1.0001635551452637, 1.0044846534729004]So far we have collected the time taken for loop, list and map iterations. We can use the data to visualize. We can use the library matplotlib. Let us do this with 300 as n.
到目前为止,我们已经收集了循环,列表和映射迭代所花费的时间。 我们可以使用数据进行可视化。 我们可以使用matplotlib库。 让我们以300为n来执行此操作。
import timeimport matplotlib.pyplot as pltdef func(x): return xdef func_for(item): resultant_list = [] start_time = time.time()for m in item: resultant_list.append(m) time.sleep(1) end_time = time.time()return end_time - start_timedef func_list(item): start_time = time.time()resultant_list = [m for m in item] time.sleep(1) end_time = time.time()return end_time - start_timedef func_map(item): start_time = time.time()resultant_object = map(func, master_list) time.sleep(1) resultant_list = list(resultant_object) end_time = time.time()return end_time - start_timetime_for_loop = []time_list_comp = []time_map_fun = []x_axis = []n = int(input("Enter a Limit:"))for t in range(1,n-1): x_axis = [r for r in range(n)]for x in range(1,n): master_list = [a for a in range(x)] time_for_loop.append( func_for( master_list ) ) time_list_comp.append( func_list( master_list ) ) time_map_fun.append( func_map( master_list ) )fig = plt.figure(figsize=(10, 8))plt.plot(x_axis, time_for_loop, label='For')plt.plot(x_axis, time_list_comp, label='List')plt.plot(x_axis, time_map_fun, label='Map')plt.legend()plt.show()fig.savefig('graph.png')To improving the better data quality we have used the sleep() method. So it will take long time for large number of n value.
为了提高更好的数据质量,我们使用了sleep()方法。 因此,大量的n值将花费很长时间。
Data Visualization 数据可视化 n = 10000 n = 10000Data visualization is one of the best thing to understand the data story better. The above graph will give you the insight of how different iterative methods performed in different elements.
数据可视化是更好地理解数据故事的最佳方法之一。 上面的图表将使您了解在不同元素中如何执行不同的迭代方法。
Complete Program 完成程序We can’t choose the best method for iterating methods directly. Everything depends on the use case. By comparing the curves from the graph we conclude that list comprehension is the best among three. As that’s true. List comprehension is a best option to create list data type.
我们不能直接选择最佳方法来迭代方法。 一切都取决于用例。 通过比较图中的曲线,我们得出结论,列表理解是三者中最好的。 的确如此。 列表理解是创建列表数据类型的最佳选择。
But when I was start coding this program, the map function was the best one before converting into a list. Map returns map object and it gives great flexibility on accessing functions. If the performance of program is your goal choosing list comprehension, for aesthetics use mapping concept.
但是,当我开始对该程序进行编码时,在转换为列表之前,map函数是最好的。 Map返回map对象,它在访问函数时具有极大的灵活性。 如果程序的性能是您选择列表理解的目标,那么出于美学考虑,请使用映射概念。
Coming to the for loop, the fluctuations in the graph is due to the system performance which may vary for everyone. The for loop is a linear implementation of code. That follows O(n) complexity. Than you for your precious time.I hope you learned something useful in this article. Please, mention any other article you need on programming. ❤️❤️❤️
进入for循环,图表中的波动是由于系统性能而引起的,该性能可能因每个人而异。 for循环是代码的线性实现。 这遵循O(n)的复杂性。 感谢您的宝贵时间。希望您从本文中学到了一些有用的信息。 请提及您需要编程的其他文章。 ❤️❤️❤️
My other articles you might be interested.
我的其他文章您可能会感兴趣。
翻译自: https://towardsdatascience.com/loop-vs-list-comprehension-vs-map-in-python-73479bd85c5a
python map循环
相关资源:四史答题软件安装包exe