如何在Python中从文本文件生成的嵌套列表中选择列表项

2024-05-15 02:39:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件说

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']

如何将print语句转换为print mash[1]。我无法将这些值存储在python idle中,因此我需要一些方法来询问如何从mash打印25.50?你知道吗


Tags: inforlineplusenhancedprintmash文本文件
3条回答

您可以更改初始列表以将其存储在字典中:

def readfile():
    dictionary = { data[0]: [float(data[1], float(data[2])] for data in [line.split(',') for line in open("chookfood.txt", 'r')]
    print(dictionary)

您可以通过以下方式访问Mash的第一个元素:

print(dictionary[“Mash”][0])

您已经有一个包含内容的列表列表。您只需从函数返回列表,然后使用列表索引访问内容:

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'

如果它们是逗号分隔的值,请使用^{}模块:

import csv

with open('chookfood.txt') as chookfood:
    rows = csv.reader(chookfood)
    for row in rows:
        print(row[1])

相关问题 更多 >

    热门问题