[英]python sort strings with digits in the beginning
I have a list like this我有一个这样的清单
list = [Tree, Plant, Bird, 7animal, Beta, 4qwerty]
when I use sorted it gives me output like当我使用 sorted 时,它给了我类似的输出
sorted(list) = [Beta, Bird, Plant, Tree, 4qwerty, 7animal]
But I want output some thing like this但我想输出这样的东西
[Beta, Bird, 4qwerty, 7animal, Plant, Tree]
Since I want to consider 4=d
and 7=g
.因为我想考虑
4=d
和7=g
。 Ex: I want to consider {1=a, 2=b, 3=c, 4=d,....26=z}
How to achieve this ?例如:我想考虑
{1=a, 2=b, 3=c, 4=d,....26=z}
如何实现?
def sort_list(list):
return sorted(list)
I think, you could replace that digit
with a mapping
like,我想,你可以用这样的
mapping
替换那个digit
,
import re
import string
mapping = {str(idx): x for idx, x in enumerate(string.ascii_uppercase, 1)}
def key_func(val):
match = re.search(r'^\d+', val)
if match:
digit = match.group()
val = val.replace(digit, mapping[digit])
return val
stuff = ['Tree', 'Plant', 'Bird', '7animal', 'Beta', '4qwerty']
x = sorted(stuff, key=key_func)
print(x)
['Beta', 'Bird', '4qwerty', '7animal', 'Plant', 'Tree']
Incoming a Old-Schooler :新来的老学生:
Explanation :说明:
Fucntion NormalizeStrings()
to get respect value of the digit starting strings from the dictionary and append accordingly.函数
NormalizeStrings()
从字典中获取数字起始字符串的尊重值并相应地附加。
Function replaceString()
to replace the values from the dict_
函数
replaceString()
替换dict_
的值
Function DeNormalizeStrings()
to do opposite of NormalizeStrings()
函数
DeNormalizeStrings()
与NormalizeStrings()
相反
Function DereplaceString()
to to do opposite of replaceString()
函数
DereplaceString()
与replaceString()
相反
alist = ['Tree', 'Plant', 'Bird', '7animal', 'Beta', '4qwerty']
alist2 = []
dict_ = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i',
10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r',
19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
def replaceString(s):
return s[0].replace(s[0],dict_[int(s[0])])
def NormalizeStrings(alist):
for s in alist:
if s[0].isdigit():
s = replaceString(s) + s[1:]
alist2.append(s)
else:
alist2.append(s)
def DeReplaceString(s):
for name in dict_:
if dict_[name] == s[0]:
return s[0].replace(s[0], str(name))
def DeNormalizeStrings(alist):
alist2.clear()
for s in alist:
if s[0].islower():
s = DeReplaceString(s) + s[1:]
alist2.append(s)
else:
alist2.append(s)
NormalizeStrings(alist)
print(alist2)
print(sorted(alist2, key=lambda s: s.lower()))
DeNormalizeStrings(sorted(alist2, key=lambda s: s.lower()))
print(alist2)
OUTPUT:输出:
['Tree', 'Plant', 'Bird', 'ganimal', 'Beta', 'dqwerty']
['Beta', 'Bird', 'dqwerty', 'ganimal', 'Plant', 'Tree']
['Beta', 'Bird', '4qwerty', '7animal', 'Plant', 'Tree']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.