我有一个文本文件说
Mash,25.50,108.00
Enhanced,37.50,162.00
Pellets,30.00,135.00
Protein Plus,39.00,174.00
Calcium Plus,39.00,174.00
我将它运行到打印语句中
def readfile():
textlist = [line.split(',') for line in open("chookfood.txt", 'r')]
print(','.join([str(lst) for lst in textlist]))
readfile()
它输出这个嵌套列表:
['Mash', '25.50', '108.00\n'],['Enhanced', '37.50', '162.00\n'],['Pellets', '30.00', '135.00\n'],['Protein Plus', '39.00', '174.00\n'],['Calcium Plus', '39.00', '174.00']
如何制作打印语句来打印 mash[1]。我无法将这些值存储在 python idle 中,所以我需要以某种方式询问如何从 mash 打印 25.50?
请您参考如下方法:
您已经有了包含内容的列表列表。您只需要从函数返回列表,然后使用列表索引访问内容:
def readfile():
textlist = [line.split(',') for line in open("test.txt", 'r')]
return textlist
l = readfile()
print(l)
#Output:
[['Mash', '25.50', '108.00\n'],
['Enhanced', '37.50', '162.00\n'],
['Pellets', '30.00', '135.00\n'],
['Protein Plus', '39.00', '174.00\n'],
['Calcium Plus', '39.00', '174.00']]
然后,只需使用列表索引:
l[0][1]
#'25.50'
