gpt4 book ai didi

python - 如何用列表中的最小索引替换特定整数

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:38 25 4
gpt4 key购买 nike

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

我的代码是:

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 block 中:

try:
lst[lst.index(13)] = 100
except ValueError:
print('Value does not exist in list')

关于python - 如何用列表中的最小索引替换特定整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52774490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com