我有一个这样的列表
list = [Tree, Plant, Bird, 7animal, Beta, 4qwerty]
当我使用排序时,它会给我类似
的输出sorted(list) = [Beta, Bird, Plant, Tree, 4qwerty, 7animal]
但是我想输出类似这样的东西
[Beta, Bird, 4qwerty, 7animal, Plant, Tree]
由于我要考虑4=d
和7=g
。
例如:我想考虑{1=a, 2=b, 3=c, 4=d,....26=z}
如何实现呢?
def sort_list(list):
return sorted(list)
答案 0 :(得分:1)
我认为,您可以将digit
替换为mapping
,例如
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']
答案 1 :(得分:0)
传入 老学校 :
说明:
功能NormalizeStrings()
从字典中获取数字起始字符串的尊重值,并相应地附加。
函数replaceString()
替换dict_
中的值
函数DeNormalizeStrings()
与NormalizeStrings()
相反
功能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)
输出:
['Tree', 'Plant', 'Bird', 'ganimal', 'Beta', 'dqwerty']
['Beta', 'Bird', 'dqwerty', 'ganimal', 'Plant', 'Tree']
['Beta', 'Bird', '4qwerty', '7animal', 'Plant', 'Tree']