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

2024-09-17 18:19:59 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,假设我有一个如下列表

list = ['list4','this1','my3','is2'] or [1,6,'one','six']

所以现在我想更改每个元素的索引,使其与数字匹配,或者在我认为合适的情况下有意义(不需要是数字),就像这样,(基本上将元素的索引更改为我想要的任何位置)

list = ['this1','is2','my3','list4'] or ['one',1,'six',6]

不管有没有数字,我该怎么做

请帮忙,提前谢谢


Tags: or元素列表情况数字onelist意义
3条回答

对于第一个,这很简单:

>>> lst = ['list4','this1','my3','is2']
>>> lst = sorted(lst, key=lambda x:int(x[-1]))
>>> lst
['this1', 'is2', 'my3', 'list4']

但这假定每个项都是字符串,并且每个项的最后一个字符都是数字。只要每个项目中的数字部分是个位数,它也可以工作。否则它就坏了。对于第二个问题,您需要定义“您如何看待它”,以便按照逻辑对其进行排序

如果有多个数字字符:

>>> import re
>>> lst = ['lis22t4','th2is21','my3','is2']
>>> sorted(lst, key=lambda x:int(re.search(r'\d+$', x).group(0)))
['is2', 'my3', 'list4', 'this21']
# or,
>>> ['is2', 'my3', 'lis22t4', 'th2is21']

但你总是可以做到:

>>> lst = [1,6,'one','six']
>>> lst = [lst[2], lst[0], lst[3], lst[1]]
>>> lst
['one', 1, 'six', 6]

另外,不要使用python内置函数作为变量名list是一个错误的变量名

如果您只想将列表中“y”位置的元素移动到“x”位置,您可以使用pop和insert尝试此一行:

lst.insert(x, lst.pop(y))

如果您不想使用regex并学习它的迷你语言,请使用以下更简单的方法:

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

相关问题 更多 >