python 对输入的单词进行字典排序_在Python中按字典顺序对单词进行排序

按字典顺序对单词进行排序意味着我们要首先按单词的第一个字母排列它们。然后,对于第一个字母相同的单词,我们将它们按第二个字母排列在该组中,依此类推,就像在语言的词典中一样(不是数据结构)。

Python有2个函数,按照这种类型的顺序进行排序和排序,让我们看看如何以及何时使用这些方法。

就地排序:当我们要对数组/列表进行就地排序时,即更改当前结构本身的顺序时,可以直接使用sort方法。例如,my_arr = [

"hello",

"apple",

"actor",

"people",

"dog"

]

print(my_arr)

my_arr.sort()

print(my_arr)

这将给出输出-['hello', 'apple', 'actor', 'people', 'dog']

['actor', 'apple', 'dog', 'hello', 'people']

如您所见,原始数组my_arr已被修改。如果要保持此数组不变并在排序时创建一个新数组,则可以使用sorted方法。例如,

示例my_arr = [

"hello",

"apple",

"actor",

"people",

"dog"

]

print(my_arr)

# Create a new array using the sorted method

new_arr = sorted(my_arr)

print(new_arr)

# This time, my_arr won't change in place, rather, it'll be sorted

# and a new instance will be assigned to new_arr

print(my_arr)

输出结果

这将给出输出-['hello', 'apple', 'actor', 'people', 'dog']

['actor', 'apple', 'dog', 'hello', 'people']

['hello', 'apple', 'actor', 'people', 'dog']

如您所见,原始数组未更改。

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值