gpt4 book ai didi

python - 如何应用条件来更改变量列表的值? - Python

转载 作者:行者123 更新时间:2023-12-02 18:04:24 25 4
gpt4 key购买 nike

我试图允许这些预定义变量的值根据用户的输入进行更改。

我最近遇到了 map() 函数,并且尝试使用它,尽管我不确定我是否正确使用了它。

在此代码中,我尝试减少数字列表的百分比,然后根据用户输入输出这些修改后的数字。

a = 1
b = 2
c = 3

list = [a, b, c]

i = 0

def percentage(n):
while i < 7:
n= n*20/100
i+=1

sample = input("Enter a string: ")

if sample == "Fox":
map(percentage, list)


cat1 = f"The fox ran at a speed of {a}."
cat2 = f"The shark swam at a speed of {b}."
cat3 = f"The bird flew at a speed of {c}."

print(cat1, cat2, cat3)
print(list)

这是输出:

Enter a string: Fox 
The fox ran at a speed of 1. The shark swam at a speed of 2. The bird flew at a speed
of 3.
[1, 2, 3]

我所做的并没有改变这些值。我做错了什么吗?如果没有,我怎样才能在这里实现我想要实现的目标?

最佳答案

一些错误,已在下面修正并附有注释,以帮助您了解问题所在。

a = 1
b = 2
c = 3

# Do not use buildins as variable names. Renamed to mylist
mylist = [a, b, c]



def percentage(n):
i = 0 # i shouldnt be a global variable, so move it here.
while i < 7:
n= n*20/100
i+=1 # keep iterating in loop, or you will loop forever
return n # function needs to return value, without it you would get [None,None,None]

sample = input("Enter a string: ")

if sample == "Fox":
# Map does not change list "in place", it returns map.
# You need to transform it to list and assign it to "mylist"
mylist = list(map(percentage, mylist))


cat1 = f"The fox ran at a speed of {a}."
cat2 = f"The shark swam at a speed of {b}."
cat3 = f"The bird flew at a speed of {c}."

print(cat1, cat2, cat3)
print(mylist)

输出

Enter a string: Fox
The fox ran at a speed of 1. The shark swam at a speed of 2. The bird flew at a speed of 3.
[1.28e-05, 2.56e-05, 3.84e-05]

关于python - 如何应用条件来更改变量列表的值? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73634115/

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