python程序设计基础教程(python语言程序设计基础(第2版))
发布网友
发布时间:2024-08-20 12:16
我来回答
共1个回答
热心网友
时间:2024-08-29 19:31
python程序设计基础教程,python语言程序设计基础(第2版)。小编来告诉你更多相关信息。
例4
一个所有元素都不相等的列表和一个整数n,要求:以n这一数值为准,将大于n的数值放在n的前面,小于n的数值放在n的后面并形成一个新列表。
思路
通过遍历原来的列表,将大于n的数值放在新建列表1中,小于n的数值放在新建列表2中,最后将新建列表1、n、新建列表2拼接组合。
方法
方法1:通过遍历将符合要求的数值使用append()方法添加到新列表中,优势在于时间节省,在此方法中,列表只需遍历一次。
方法2:通过列表推导式判断数值的大小并分类。
期待这个冬天
定义函数func()。位置参数List,待处理列表;n,判断大小的标准数值。新建列表1,2。对List的元素i进行遍历,与n进行比较,大于n是数值放在list1,小于n的数值放在list2并通过append()方法放置。最后将两个新列表和列表【n】进行拼接。
英文翻译
Example 4. A list with unequal elements and an integer n. The requirements: take the value of n as the standard, put the value greater than n before n, and the value less than n after n and form a new List.
Idea: By traversing the original list, put the values greater than n in the new list 1, and the values less than n in the new list 2, and finally combine the new list 1, n, and the new list 2.
Method 1: Use the append() method to add the required values to the new list through traversal. The advantage is time saving. In this method, the list only needs to be traversed once.
Method 2: Determine the size of the value and classify it through a list deduction.
Code: Define the function func(). Position parameter List, the list to be processed; n, the standard value for judging the size. Create a new list 1, 2. The element i of List is traversed and compared with n. The value greater than n is placed in list1, and the value less than n is placed in list2 and placed through the append() method. Finally, the two new lists and list [n] are spliced together.
参考资料:《python程序设计基础》董付国
翻译:Gogol翻译