【题解】Chapter 10 Quiz (Python Data Structures)

吐槽:我只想记录俩题,其他的都很简单就不说了。主要其实是想弄个概念辨析的,不过最后还是改成了题解hhh

题目:

2. Which of the following methods work both in Python lists and Python tuples?

A reverse()

B pop()

C append()

D sort()

E index()

答案:E。元组没有ABCD,只有E,列表是全有。reverse()(https://www.runoob.com/python/att-list-reverse.html)pop()(https://www.runoob.com/python/python-att-dictionary-pop.html)append()(https://www.runoob.com/python3/python3-att-list-append.html)sort()(https://www.runoob.com/python/att-list-sort.html)index()(https://www.runoob.com/python/att-list-index.html)

7. If the variable data is a Python list, how do we sort it in reverse order?

A data.sort(reverse=True)

B data = sortrev(data)

C data = data.sort(-1)

D data.sort.reverse()

答案:A。没有B中的函数。C的话,sort() 没有返回值,另外,python3.x中取消了cmp参数,也不支持直接往sort()里面传函数,但可以构造排序函数传递给key来实现,关于key和lambda函数可以看这(https://zhuanlan.zhihu.com/p/67978661?utm_source=qq&utm_medium=social&utm_oi=56920941527040)。乍一看感觉D好像也对,但是 list.sort() 本身是没有返回值的,list.reverse() 就相当于没有操作列表所以会报错。顺便说一下 list.sort() 和 sorted(list),首先是返回值的区别:前者没有返回值后者返回值是列表,其次是 sorted() 可以对所有可迭代的对象进行排序操作(https://www.runoob.com/python/python-func-sorted.html)。

我想说的:

1,元组和列表的区别:总的来说,列表和元组都是有序的,可以存储任意数据类型的集合,区别主要在于下面的两点:

1)列表是动态的,长度可变,可以随意的增加、删减或改变元素,列表的存储空间略大于元组,性能略差与元组

2)元组是静态的,长度大小固定,不可以对元素进行增加、删减或改变操作,元组相对于列表更加轻量级,性能稍优

(https://www.cnblogs.com/yuyafeng/p/11150459.html)。

2,python中数据结构的有序和可变性:列表有序可变,字典无序不可变,元组不可变,集合无序不可变,数字不可变,字符串不可变(https://www.cnblogs.com/z-x-y/p/10090749.html)。

补充:

2020/3/10:如果lst = [1, 2, 3] 但运行lst[100] = 5 肯定会报错;但如果dic = {1: 1, 2: 2} 运行dic[100] = 5,则不会报错,而是赋值,相当于添加了一个键值对。

你可能感兴趣的:(Python,题解)