繁体   English   中英

试图找出将多行处理成字典的正确循环

[英]Trying to figure out the correct loop for processing multiple lines into a dictionary

grocery_stock.txt包含

lemonade 6 1.1

bread 34 1.43

chips 47 3.76

banans 16 0.79

pizza 15 5.0

到目前为止,这是我为此编写的代码。

    infile=open("grocery_stock.txt", 'r+')
    lines=infile.readlines()
    line=infile.readline()
    none= ' '
    count = 0
    index= 0
    while line !=none:
        line1=infile.readline()

        while line1 in lines:

            line1=line1.split()
            name1=str(line1[:0])
            quant1=(str(line1[:1]))
            price1=[(str(line1[:2]))]
            grocerystock[name1[0]]=(quant1,name1)

            print (grocerystock)

        line2=infile.readline()
        for line2 in line:
            line1=line2.split()
            name1=str(line1[0])
            quant1=(str(line1[1]))
            price1=[(str(line1[2]))]
            grocerystock[name1[1]]=(quant1,name1)
            print (line1[1], line[2],line1[0])
            print (grocerystock)

        line3=infile.readline()
        line4=infile.readline()
        line5=infile.readline()
    infile.close()

    grocerystock={} 

我这样做的原因是因为稍后在我的项目中,我将必须删除一些键并更改一些值,以便我想要一个可以在我读取文件以将数据转换为字典时在程序中任意调用的函数。

我的循环对您来说可能看起来很疯狂,但是我正要尝试尝试突然出现的任何事情。

另外,如您所见,我还没有完成第5行,我认为找出正确的循环而不是键入随机循环并看看会发生什么会更好。

先感谢您。

也许这会有所帮助:

with file('grocery_stock.txt') as f:
    lines = f.readlines()

# filter out empty lines
lines = [line for line in lines if line.strip() != '']

# split all lines
lines = [line.split() for line in lines]

# convert to a dictionary
grocerystock = dict((a, (b, c)) for a, b, c in lines)

# print
for k, v in grocerystock.items():
    print k, v

您唯一需要的循环是逐行移动数据的循环。 可以这样实现:

with open("grocery_stock.txt", "r+") as f:
    for line in f: # Changed to be a more elegant solution; no need to use while here.
        # Here we would split (hint) the line of text.
        dict[split_text[0]] = [split_text[1], split_text[2]]

既然是家庭作业,我鼓励您和其他人一起研究此解决方案。 我不能只你答案,现在可以吗?

只是一些提示,因为这是硬件:

  • 尝试使用上下文管理器打开文件,即with 语句
  • 即使while并没有错,在这种情况下,我还是更喜欢使用for循环(迭代次数是固定的-行数)–我有时将while循环视为解决暂停问题的途径 ...
  • 尝试使用readlines() ,因为行数可能很小; 或使用类似以下的内容(看起来很自然):

     for line in f: # do something with line 

当使用open()并获得文件对象时,可以仅在文件对象上进行迭代。 像这样:

for line in f:
    # do something with the line

我建议使用上面的方法,而不是循环调用f.readline()

f.readlines()会将整个文件读入内存,并构建输入行列表。 对于非常大的文件,这可能会导致性能问题。 对于您在此处使用的小文件,它可以工作,但是如果您学习标准的Python习惯用法,则可以将其用于小文件或大文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM