例如假设我有如下列表,
list = ['list4','this1','my3','is2'] or [1,6,'one','six']
所以现在我想更改每个元素的索引以匹配数字或使我认为合适(不必是数字)像这样,(基本上将元素的索引更改为我想要的任何位置)
list = ['this1','is2','my3','list4'] or ['one',1,'six',6]
无论是否有数字,我该怎么做?
请帮助,在此先感谢。
最佳答案
如果您不想使用正则表达式并学习它的迷你语言,请使用这种更简单的方法:
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 - 如何在不删除/更改原始元素及其值的情况下将列表/数组中元素的索引更改为另一个位置/索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65773707/