是否可以将列表中的数字项目更改为同一


list = ['_ ','_ ','_ ','_ ','_ ']   
index = [1,4]
letter = 'm'

那么,使用索引和字母吗?

感谢您的帮助!

您去这里:

for i in index:
    list[i] = letter

许多解决方案在此处使用loop尝试相同的旧方法:

这是不同的方法:

没有任何循环:

list_1 = ['_ ','_ ','_ ','_ ','_']
index = [1,4]
letter = 'm'
list(map(lambda x:(list_1.__setitem__(x,letter)),index))
print(list_1)

输出:

['_ ', 'm', '_ ', '_ ', 'm']

一些饼干:

import operator
list(map(lambda x:operator.setitem(list_1, x, letter),index))
print(list_1)

输出:

['_ ', 'm', '_ ', '_ ', 'm']

是的,您要实现的目标被称为花式索引 - 使用索引列表。但是,这对于numpy数组而不是简单的python列表而不是。因此,可能的解决方案冷为:

import numpy as np
mylist = ['_ ','_ ','_ ','_ ','_ ']
index = [1,4]
letter = 'm'
list_changed=np.array(mylist)
list_changed[index]=letter
print list_changed

相关内容

最新更新