list1 = ['list4','this1', 'he5re', 'my3','is2']
def mySort(string):
if any(char.isdigit() for char in string): #Check if theres a number in the string
return [float(char) for char in string if char.isdigit()][0] #Return list of numbers, and return the first one (we are expecting only one number in the string)
list1.sort(key = mySort)
print(list1)
对于第一个,这很简单:
但这假定每个项都是字符串,并且每个项的最后一个字符都是数字。只要每个项目中的数字部分是个位数,它也可以工作。否则它就坏了。对于第二个问题,您需要定义“您如何看待它”,以便按照逻辑对其进行排序
如果有多个数字字符:
但你总是可以做到:
另外,不要使用python内置函数作为变量名
list
是一个错误的变量名如果您只想将列表中“y”位置的元素移动到“x”位置,您可以使用pop和insert尝试此一行:
如果您不想使用regex并学习它的迷你语言,请使用以下更简单的方法:
受到这个答案的启发:https://stackoverflow.com/a/4289557/11101156
相关问题 更多 >
编程相关推荐