简体   繁体   English

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

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

So I am trying to change value at specific index to every element in list.所以我试图将特定索引处的值更改为列表中的每个元素。

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

What I want to do is change every element's value at index 3 with f variable我想要做的是使用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: Output:

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

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

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