python - 用户输入列表是否等同于普通列表?
问题描述
import random
def ifKilled(bullet, hp, target):
shot=False
length=len(hp)
while bullet>0 and hp[target]!=0:
bullet-=1
hp[random.randrange(length)] -= 1
if hp[target]==0:
shot=True
return shot
input1 = input('Enter the hp of all possible target:')
input2 = int(input('Enter the target:'))
finput1 = [int(n) for n in input1.split(' ')]
print(finput1)
print("target is:"+str(input2))
c=0
t=0
while c<1000:
#if ifKilled(3, [30,2],1):
if ifKilled(3, finput1, input2):
t+=1
#print(str(t))
c+=1
print(t/1000)
上面的代码 ifKilled 需要一个列表和一个 int 作为参数,但是当我通过硬编码输入一个列表时,它给了我一个与用户输入列表不同的答案(两个列表都是 [30,2])。我在获取用户列表时做错了什么吗?我所做的是在输入中输入 302,它应该得到一个与 [30,2] 列表相同的列表,对吗?
解决方案
根本原因是你在函数hp
内部改变了参数ifKilled
。
当您将finput1
list 传递给 时ifKilled
,它会在while
循环的迭代中重用。
当您传递[30, 2]
到 时,它会为每次迭代重新创建,因此不会保存ifKilled
对它的任何更改。ifKilled
推荐阅读
- python - 结合两个机器学习模型的结果
- spring-boot - 执行器指标标签 PathVariable 和通配符
- python - 在python中解决与二维矩阵相关的问题的最有效方法
- cordova - Google Play 控制台未读取 Meteor minSdkVersion
- html - Watir 找不到自动填充的 div 元素
- python - AxisError:轴 1 超出维度 1 数组的范围
- java - Java:它一直说“变量 yn 可能尚未初始化”
- r - 不一致阵列的突变
- angular - Angular NGX图表:调整X刻度数
- javascript - 以什么形式在客户端保留聊天列表及其消息