我有一些串列 A = ['a', 'b', 'c', 'd', 'e', 'f'] 我需要按這個順序獲取元素的索引 0 1 1 2 2 3 3 4 4 5
但是我的代碼做了這個命令 0 1 2 3 4 5
A = ['a', 'b', 'c', 'd', 'e', 'f']
for i in A:
print(A.index(i), end=' ')
uj5u.com熱心網友回復:
如果您有所需的索引,為什么不試試這個:
X = [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]
A = ['a', 'b', 'c', 'd', 'e', 'f']
for i in X:
print(A[i], end=' ')
uj5u.com熱心網友回復:
使用串列理解來提取與索引對應的值。
X = [0, 1, 1, 2, 2, 3, 3, 4, 4, 5]
A = ['a', 'b', 'c', 'd', 'e', 'f']
new_list = [A[x] for x in X]
更新
如何從串列串列中制作平面串列用于展平嵌套串列
list_of_list = [[x,x] for x in range(1,len(A))]
new_list = [0] [item for sublist in list_of_list for item in sublist]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/328985.html
上一篇:Haskell對整數串列求和
下一篇:如何修復代碼中的輸出問題?
