python3中字符串、列表、字典的排序

来源:互联网 发布:python csv使用 编辑:程序博客网 时间:2024/05/17 08:24

1、字符串排序

>>> s = 'string'>>> m = sorted(s)>>> s'string'>>> m['g', 'i', 'n', 'r', 's', 't']`

把字符串直接转换成列表的形式进行排序了,原字符串不变。

2、列表排序
第一种方法:不改变原来的值

>>> l = [5, 2, 4, 3]>>> l2 = sorted(l)>>> l[5, 2, 4, 3]>>> l2[2, 3, 4, 5]

通过使用sorted()方法把原来的列表进行排序,生成一个新的排序列表,原字符串不变。

第二种方法:直接在原来的列表上进行排序

>>> l = [5, 2, 4, 3]>>> l2 = l.sort()>>> l[2, 3, 4, 5]>>> print(l2)None

通过用列别的内嵌方法sort()直接在原来的列表上进行排序,不生成新的列表。

3、字典排序

>>> k = {5:'li', 3:'wang', 6:'zhao', 4:'han'}>>> k2 = sorted(k)>>> k{3: 'wang', 4: 'han', 5: 'li', 6: 'zhao'}>>> k2[3, 4, 5, 6]

用sorted()方法直接在原来的字典上进行排序,字典和字符串都没有内嵌sort()方法。

原创粉丝点击