开发者

Sorting a python array

开发者 https://www.devze.com 2023-01-11 13:31 出处:网络
opt=[] opt=[\"opt3\",\"opt2\",\"opt7\",\"opt6\",\"opt1\"] for i in range(len(opt)): print opt[i] Output for the above is
opt=[]
opt=["opt3","opt2","opt7","opt6","opt1"]
for i in range(len(opt)):
     print opt[i]

Output for the above is

opt3,op开发者_运维知识库t2,opt7,opt6,opt1

How to sort the above array in ascending order..


Use .sort() if you want to sort the original list. (opt.sort())

Use sorted() if you want a sorted copy of it.


print sorted(opt)


Depends on whether or not you want a natural sort (which I think you do) or not.

If you use sorted() or .sort() you'll get:

>>> opt = ["opt3", "opt2", "opt7", "opt6", "opt1", "opt10", "opt11"]
>>> print sorted(opt)
['opt1', 'opt10', 'opt11', 'opt2', 'opt3', 'opt6', 'opt7']

While you'll probably want ['opt1', 'opt2', 'opt3', 'opt6', 'opt7', 'opt10', 'opt11'].

If so you'll want to look into natural sorting (there are various variations on the function mentioned in that article).

0

精彩评论

暂无评论...
验证码 换一张
取 消