python - 如何在不删除/更改原始元素及其值的情况下将列表/数组中元素的索引更改为另一个位置/索引

标签 python python-3.x list

例如假设我有如下列表,

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)

受此答案启发:https://stackoverflow.com/a/4289557/11101156

关于python - 如何在不删除/更改原始元素及其值的情况下将列表/数组中元素的索引更改为另一个位置/索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65773707/

相关文章:

python - 在python中显示2D数独板

python - 在 sqlalchemy 中的查询级别连接列

python - 将字典作为 mysql.connector 的参数传递

python - 将连续的数字组合成范围元组

python - 使列表与另一个列表 python 完全匹配

python - 如何将带有重复文本的 CSV 列拆分为每个可能的文本变体的 0-1 列?

python - 如何从 Python 列表中选择一组变量

python - 如何锁定 python (.py) 文件进行编辑?

python - 如何按特定规则排序 django

C++ 原子列表容器