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

问题描述

所以我试图将特定索引处的值更改为列表中的每个元素。

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)

输出:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...