[英]Shuffle array such that the expected index of an element will be its original index
[英]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)
對於第一個,這很容易:
>>> 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.