![](/img/trans.png)
[英]Replacing the elements in list at the positions given in replacement indices with new value in Python
[英]Replacing a list of indices with a string in python
我在列表中有一組索引:
[2 0 3 4 5]
我想用存儲在另一個列表中的值替換它們:
[a b c d e f g]
並輸出:
[c a d e f]
我嘗試了這段代碼:
for line in indices:
print(line)
for value in line:
value = classes[value]
print(line)
break
它將兩次打印原始列表。 有沒有辦法替換元素,還是我被迫創建一個新的列表列表?
這看起來是使用列表理解的好地方,請嘗試以下方法-慣用的解決方案:
idxs = [2, 0, 3, 4, 5]
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
[chars[i] for i in idxs]
=> ['c', 'a', 'd', 'e', 'f']
當然,我們可以按照您的預期使用顯式循環執行相同的操作,但是它不像以前的解決方案那么酷:
ans = []
for i in idxs:
value = chars[i]
ans.append(value)
ans
=> ['c', 'a', 'd', 'e', 'f']
作為最后的選擇-我不知道您為什么要在輸入列表中“替換元素”(如問題所述),但是可以肯定,這也是可能的,但不建議這樣做-創建起來更簡單,更簡潔一個帶有答案的新列表(如前兩個片段所示),而不是更改原始輸入:
for pos, val in enumerate(idxs):
idxs[pos] = chars[val]
idxs
=> ['c', 'a', 'd', 'e', 'f']
idxs = [2, 0, 3, 4, 5]
chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
map(lambda x : chars[x],idxs)
=> ['c', 'a', 'd', 'e', 'f']
要么
reduce(lambda x,y: x+[chars[y]],idxs,[])
=> ['c', 'a', 'd', 'e', 'f']
您還可以使用chr()
函數將int轉換為字符(ascii表)
>>> a = [2 0 3 4 5]
>>> [chr(i+97) for i in a]
['c', 'a', 'd', 'e', 'f']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.