sort()、reverse() 是列表的方法,直接对原列表进行操作。sorted() 是函数,其返回的是一个新的列表。==========================difang=['d','c','b','a']difang.sort()difang.sort(reverse=True)x=sorted(difang,reverse=True)print(difang)print(x)
AttributeError: 'tuple' object has no attribute 'sort' >>> sorted(b) # sorted对元组同样起作用 [2, 3, 5, 7, 8] 1. 2. 3. 4. 5. 6. 7. 8. 三、key参数/函数 从python2.4开始,list.sort()和sorted()函数增加了key参数来指定一个函数,此函数将在每个元素比较前被调用。 例如通过key指定...
类似地,如果我们对字符串调用reverse()方法的话则会报错,为'str' object has no attribute 'reverse'。2.4 使用sorted函数 sorted() 函数可以对可迭代对象进行排序,而且还可以指定排序规则。当我们将可迭代对象按照相反的顺序排序时,即可实现逆序输出。例如: my_list = [1, 2, 3, 4, 5]reversed_list =...
TypeError:'range'objectisnotan iterator>>>I1 =iter(R)>>>next(I1)0>>>next(I1)1>>>I2 =iter(R)>>>next(I2)0>>> zip, map, filter不支持相同结果上的多个活跃迭代器 >>>z =zip([1,2,3],['a','b','c'])>>>list(z) [(1,'a'), (2,'b'), (3,'c')]>>>I1 =iter(z...
2、sorted() 作用于任意可迭代的对象,而 sort()一般作用于列表。 >>> a = (1,2,4,2,3)>>> a.sort()Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: 'tuple' object has no attribute 'sort'>>> sorted(a)[1, 2, 2, 3, 4] 下面的例子中针对...
1>>>a=['a','f','c','x','e']2>>>a_new=sorted(a,reverse=True)3>>>a_new4['x','f','e','c','a'] 对元组进行排列,不能使用list.sort()函数: 1>>>a=('a','f','c','x','e')2>>>a_new=a.sort()34ttributeError:'tuple'object has no attribute'sort' ...
no attribute 'sort'>>>_=sorted({2: 'two', 0: 'zero', 1: 'one'})>>># sort a set>>>_=set([2, 3, 4]).sort()Traceback (most recent call last): File "<stdin>", line 1, in<module>AttributeError: 'set' object has no attribute 'sort'>>>_=sorted(set([2, 3, 4])) ...
>>>my_list.sorted()#AttributeError:'list'object has no attribute'sorted'>>>my_dict={'host':'http://bbs.fishc.com','port':'80'}>>>print(my_dict['server'])#不存在的“键”引发 KeyError:'server'异常 f=open('C:\\test.txt',wb)#注意open()第二个参数是字符串 否则引发 NameError ...
AttributeError: 'tuple' object has no attribute 'sort' >>> sorted(a) # sorted() 可以为元组排序,返回一个新有序列表 [1, 2, 2, 3, 4] >>> a=['1',1,'a',3,7,'n'] >>> sorted(a) [1, 3, 7, '1', 'a', 'n']
>>>a=(1,2,4,2,3)>>>a.sort()Traceback(most recent call last):File"<stdin>",line1,in<module>AttributeError:'tuple'object has no attribute'sort'>>>sorted(a)[1,2,2,3,4] 当排序对象为列表的时候两者适合的场景不同。sorted() 函数会返回一个排序后的列表,原有列表保持不 变;而 sort(...