簡體   English   中英

使用列表理解修改特定索引處的列表值

[英]Modify list value at specific index with list comprehension

所以我試圖將特定索引處的值更改為列表中的每個元素。

colors = [[f'#{f}10c2b']*3 for f in range(3)]
[colors[f//3][f%3][3]=f for f in range(9)]# Syntax is incorrect I am just making an example

我想要做的是使用f變量更改索引 3 處的每個元素的值

colors = [['#010c2b', '#010c2b', '#010c2b'], ['#110c2b', '#110c2b', '#110c2b'], ['#210c2b', '#210c2b', '#210c2b']] # your original list
f = "4" # the new value
index = 2  #the index of he item you want to replace
index1 = 0 #the index you are iterating on

newlist =[ [elem if index != count else f for count, elem in enumerate(list)] for list in colors]
print(newlist)

Output:

[['#010c2b', '#010c2b', '4'], ['#110c2b', '#110c2b', '4'], ['#210c2b', '#210c2b', '4']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM