gpt4 book ai didi

Python - 对于文本文件中的每个值?

转载 作者:太空宇宙 更新时间:2023-11-03 15:22:35 25 4
gpt4 key购买 nike

在我编写的代码中,我使用逗号分割了一个文本文件,现在对于其中的每个值,我想将其设为整数。我尝试过拆分文本文件,然后将其转换为整数,但这不起作用。有没有办法对文件中的所有值执行某件事?此外,值的数量并不具体,它取决于程序的用户(它是“购物 list ”程序)。我当前的代码:

TotalCOSTS=open("TotalCOSTS.txt","r")
Prices=TotalCOSTS.read()

print(Prices)
Prices.strip().split(",")
IntPrices=int(NewPrices)
print(len(IntPrices))

if len(IntPrices)==1:
print("Your total cost is: "+IntPrices +" Pounds")
elif len(IntPrices)>1:
FinalTotal = sum([int(num) for num in IntPrices.split(",")])
print("Your total cost is: "+ FinalTotal +" Pounds")

Prices 是包含值的文件,因此我删除了它的空格,然后将其拆分。这就是我需要继续前进的地方。谢谢xx

最佳答案

results = [int(i) for i in results]

Python 3 你可以做:

results = list(map(int, results))

关于Python - 对于文本文件中的每个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43414029/

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