我正在学习python,现在我在读取和分析txt文件时遇到了一些问题。我想在python中打开一个包含许多行的.txt文件,每行都有一个水果和它的价格。
我想知道如何让python将它们的价格识别为一个数字(因为当我使用readlines()时,它将其识别为一个字符串),这样我就可以在一些简单的函数中使用这些数字来计算我必须出售水果以获得利润的最低价格。
你有什么办法吗?
发布于 2011-12-15 00:42:37
如果名称和价格之间用逗号分隔:
with open('data.txt') as f:
for line in f:
name, price = line.rstrip().split(',')
price = float(price)
print name, price发布于 2011-12-15 00:50:03
假设您的值是空格分隔的,您可以使用以下命令将文件读入元组列表:
# generator to read file and return each line as a list of values
pairs = (line.split() for line in open("x.txt"))
# use list comprehension to produce a list of tuples
fruits = [(name, float(price)) for name, price in pairs]
print fruits
# will print [('apples', 1.23), ('pears', 231.23), ('guava', 12.3)]注意,float()用于将第二个值(price)从字符串转换为浮点数。
另请参阅:list comprehension和generator expression。
为了便于查找每个水果的价格,您可以将元组列表转换为字典:
price_lookup = dict(fruits)
print price_lookup["apples"]
# will print 1.23
print price_lookup["guava"] * 2
# will print 24.6请参阅:dict()
发布于 2011-12-15 00:53:21
当我第一次学习来自Perl的Python时,也遇到了同样的问题。Perl将“按您的意思去做”(或者至少是它认为您想要的那样),当您试图像使用数字一样使用它时,它会自动将看起来像数字的东西转换成数字。(我只是泛泛而谈,但你明白我的意思)。Python的哲学就是不让太多的魔术发生,所以你必须显式地进行转换。调用float("12.00")或int("123")从字符串转换。
https://stackoverflow.com/questions/8508167
复制相似问题