如何将特定整数替换为列表中的最小索引



我有一个列表[11, 12, 13, 14, 15, 16, 17, 18, 19, 13, 20 ,13],我想把它变成[11, 12, 100, 14, 15, 16, 17, 18, 19, 13, 20 ,13](用 100 替换最小索引的 13。

我的代码是:

lst= [11, 12, 13, 14, 15, 16, 17, 18, 19, 13, 20 ,13]
k='13 100'.split()
for i in range(len(lst)):
if lst[i]== int(k[0]):
lst[i]=int(k[1])
break

它有效,但我想知道另一种更简单且能够缩短执行时间的方法。 多谢!

就这么简单:

lst= [11, 12, 13, 14, 15, 16, 17, 18, 19, 13, 20, 13]
lst[lst.index(13)] = 100

它产生

[11, 12, 100, 14, 15, 16, 17, 18, 19, 13, 20, 13]

现在,如果您不确定列表中是否包含13,则可以将上述代码包装在try-except块中:

try:
lst[lst.index(13)] = 100
except ValueError:
print('Value does not exist in list')
sp_int = 13
replace_value=100
lst= [11, 12, 13, 14, 15, 16, 17, 18, 19, 13, 20, 13]
if(sp_int in lst):
lst[lst.index(sp_int)]=replace_value

上面的程序将解决您的问题。"in"运算符搜索元素,如果存在否则为 false,则返回 s true。 索引函数确定列表中指定整数的索引。

最新更新