[英]Is the claim that Python methods that use dot notation e.g. `.sort()` don't work on types other than string true?
When i was studying Python course of Codecademy, they said 'Methods that use dot notation only work with strings', so... Is .sort() method only working in String type?, or Can it sort with other types? 当我在学习Codecademy的Python课程时,他们说“使用点表示法的方法仅适用于字符串”,所以... .sort()方法仅适用于String类型吗?还是可以与其他类型进行排序? (int, float, etc)
(int,float等)
Why didn't you quickly try it yourself? 您为什么不自己快速尝试一下?
>>> l = ['c', 'b', 'a']
>>> l.sort()
>>> l
['a', 'b', 'c']
>>> l = [3, 2, 1]
>>> l.sort()
>>> l
[1, 2, 3]
>>>
Actually string or string type can't be sorted using sort()
. 实际上,不能使用
sort()
字符串或字符串类型进行排序。 For example if you choose to do like the following 例如,如果您选择执行以下操作
name = "hello"
print name.sort()
then it'll throw an error.But still if you really like to sort string or string types then try using sorted()
as shown below. 但这会引发错误。但是,如果您真的想对字符串或字符串类型进行
sorted()
尝试使用sorted()
,如下所示。
name = "hello"
print sorted(name)
output: 输出:
['e', 'h', 'l', 'l', 'o']
Note: Upper case letters take the precedence over the lower case letters while sorting. 注意:排序时,大写字母优先于小写字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.