python程序设计基础(五)
今天继续讲述列表(list)的常用方法。
共有index()、count()、reverse()、sort()、copy()五种方法。
1.index()
index(X)。返回列表中第一为X的索引值,没有则抛出异常;
2.count()
count(X)。返回列表X的个数,没有则返回0;
3.reverse()
reverse()。用于翻转列表中的元素。
4.sort()
sort()。用于对列表中的元素进行排序,可指定排序的规则,其默认规则为从小到大。
5.copy()
copy()。有浅复制和深复制之分,对于浅复制后的list1,对list1中可变数据进行改变也会改变原来的列表中的可变数据;深复制deepcopy()则可避免这种情况;若有两个变量指向同一个列表,改变任一列表数据,另一个也会改变。
推导式
简单来说,以相对简单的语句实现较为复杂的功能。
简单的例子,对1到10的数字进行平方并添加到列表 中。运用推导式可以一句语句实现。
其他功能下篇详细了解。
英文翻译
Today I will continue to talk about the common methods of lists.
There are five methods: index(), count(), reverse(), sort() and copy().
1. Index (X). Return the first index value of X in the list, if not, throw an exception;
2. Count(X). Return the number of list X, if not, return 0;
3. reverse(). Used to flip the elements in the list.
4. sort(). Used to sort the elements in the list, you can specify the sorting rules, and the default rule is from small to large.
5. Copy(). There are shallow copy and deep copy. For list1 after shallow copy, changing the variable data in list1 will also change the variable data in the original list; deep copy deepcopy() can avoid this situation; if there is Two variables point to the same list, and if you change any list data, the other will also change.
Briefly describe the list comprehension, and learn more about it in the next article.
To put it simply, relatively simple sentences are used to implement more complex functions.
Simple example, square the number from 1 to 10 and add it to the list. The use of deduction can be realized in one sentence.
参考资料:python程序设计基础(董付国)
翻译:Google翻译
本文由LearningYard新学苑原创,部分图片文字来自网络,如有侵权请联系。