首页 > 解决方案 > 用户输入列表是否等同于普通列表?

问题描述

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] 列表相同的列表,对吗?

标签: pythonpython-3.x

解决方案


根本原因是你在函数hp内部改变了参数ifKilled

当您将finput1list 传递给 时ifKilled,它会在while循环的迭代中重用。

当您传递[30, 2]到 时,它会为每次迭代重新创建,因此不会保存ifKilled对它的任何更改。ifKilled


推荐阅读