繁体   English   中英

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

[英]How to change the index of an element in a list/array to another position/index without deleting/changing the original element and its value

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

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

对于第一个,这很容易:

>>> 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是一个错误的变量名。

如果您只想将 position 'y' 中的元素移动到列表的 position 'x' 中,您可以使用 pop 和 insert 尝试这个单行:

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

如果您知道更改索引的顺序,则可以编写简单的代码:

old_list= ['list4','this1','my3','is2']
order = [1, 3, 2, 0]
new_list = [old_list[idx] for idx in order]

如果您可以将逻辑编写为 function,则可以使用sorted()并将您的 function 名称作为键传递:

old_list= ['list4','this1','my3','is2']
def extract_number(string):
    digits = ''.join([c for c in string if c.isdigit()])
    return int(digits)
    
new_list = sorted(old_list, key = extract_number)

此案例列表按数字排序,数字由字符串中的数字组合而成。

a = [1,2,3,4]

def rep(s, l, ab):
    id = l.index(s)
    q = s
    del(l[id])
    l.insert(ab, q)
    return l

l = rep(a[0], a, 2)
print(l)

希望你喜欢它更简单

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM