python 字符串列表中根据字符串内的数字进行排序。 python按字符串个数排序

python\u4e2d\u600e\u4e48\u5bf9\u6570\u5b57\u6216\u8005\u6570\u5b57\u5b57\u7b26\u4e32\u8fdb\u884c\u5b57\u5178\u65b9\u5f0f\u7684\u6392\u5e8f\uff1f

\u4ec0\u4e48\u610f\u601d\uff0c\u662f\u5b57\u7b26\u4e32\u4e5f\u53c2\u7167\u6570\u503c\u7684\u987a\u5e8f\u6392\u5e8f\u5417\uff1f

\u601d\u8def\uff1a
\u5b57\u5178\u7c7b\u578b\u7684\u5178\u578b\u7528\u6cd5\uff0c\u4f7f\u7528\u5b57\u5178\u7c7b\u578b\u6765\u7edf\u8ba1\u51fa\u73b0\u6b21\u6570\uff0c\u5b57\u7b26\u4e32\u4f5c\u4e3akey\uff0c\u51fa\u73b0\u6b21\u6570\u4f5c\u4e3avalue\u3002
\u4ee3\u7801\u5982\u4e0b\uff1a\u53ef\u4ee5\u6839\u636e\u4f60\u7684\u9700\u8981\u6539\uff0c\u8fd9\u4e2a\u662f\u628a\u5b57\u7b26\u4e32\u7684\u524d\u540e\u5bfc\u7a7a\u683c\u90fd\u53bb\u6389\u4e86\uff0c\u7a7a\u5b57\u7b26\u4e32\u4e0d\u7edf\u8ba1\u3002

PS:\u53c8\u6539\u4e86\u4e00\u4e0b\uff0c\u8fd9\u6837\u6548\u679c\u80fd\u8ddf\u597d\u70b9
# --coding:GB2312--
dic = {} #\u5b9a\u4e49\u4e00\u4e2a\u5b57\u5178\u7c7b\u578b
fp = open('data.txt') #\u6253\u5f00\u8981\u67e5\u8be2\u7684\u6587\u4ef6
for line in fp: #\u4ecefp\u4e2d\u8bfb\u53d6\u884c\uff0c\u5229\u7528\u8fd9\u79cd\u65b9\u6cd5\u53ef\u4ee5\u907f\u514d\u6709\u7a7a\u884c\u622a\u65ad\u8bfb\u53d6
line = line.strip()#\u53bb\u6389\u524d\u540e\u5bfc\u7a7a\u767d
if('' == line):
continue #\u53bb\u6389\u524d\u540e\u5bfc\u7a7a\u767d\u5982\u679c\u662f\u7a7a\u884c\u4e0d\u4f5c\u5904\u7406
if(line in dic): #\u5224\u65ads\u662f\u5426\u5728\u5b57\u5178\u5185\uff0c\u5982\u679c\u5728\u7edf\u8ba1\u52a01
dic[line] += 1
else: #\u5982\u679c\u4e0d\u5728\uff0c\u9996\u6b21\u51fa\u73b0\u7edf\u8ba1\u589e\u52a0\u65b0key\uff0c\u7edf\u8ba1\u6570\u521d\u59cb\u5316\u4e3a1
dic[line] = 1
fp.close() #\u8bfb\u5b8c\u6587\u4ef6\uff0c\u5173\u95ed\u6587\u4ef6
#\u6309value\u6392\u5e8f\uff0c\u8fd4\u56de\u662f\u4e00\u4e2a\u5143\u7ec4\u7684\u5217\u8868
afterSort = sorted(dic.items(), key=lambda dic: dic[1])
print afterSort #\u6253\u5370\u6392\u5e8f\u540e\u5217\u8868\uff0c\u53ef\u6309\u7167\u81ea\u5df1\u9700\u6c42\u63d0\u53d6\u6253\u5370

\u7ed3\u679c\uff1a
data.txt\u91cc\u5b58\u6709
qiang
song
wan
qiang
song
qiang
\u6267\u884cpython\u540e\u6253\u5370\u51fa\uff1a
[('wan', 1), ('song', 2), ('qiang', 3)]

你的列表A现在不就是按所含数字从大到小排列的吗?

不过,我还是用正则表达式的方法帮你排了一下序,如果你要数字从小到大排序,只要把alist.sort(key=sort_key,reverse=True)改成alist.sort(key=sort_key,reverse=False)就行了.

完整的Python程序如下

import re
def sort_key(s):
    if s:
        try:
            c = re.findall('\d+$', s)[0]
        except:
            c = -1
        return int(c)
def strsort(alist):
    alist.sort(key=sort_key,reverse=True)
    return alist
A=['abc 15','abd 13','abe 9','abf 6','abg 2']
print(strsort(A))



扩展阅读:python 判断 字符串 ... python字符串以什么开头 ... python 字符串转列表 ... python random ... python 字符串包含 ... python 字符串搜索 ... python 转化为列表 ... 2 字符串判等python ... python 编写函数例子 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网