简体   繁体   English

在Python中的while循环中从列表保存索引

[英]Saving an index from a list in a while loop in Python

How do you save an index of a list while in a 'while' loop? 如何在“ while”循环中保存列表的索引?

Basically I am running through a text file and I want to identify a date, and then afterwards get the information that corresponds to that date which is the line below. 基本上,我正在浏览一个文本文件,我想标识一个日期,然后再获取与该日期相对应的信息,即下面的行。 So far I can match the date entered to the line with that date but don't know how to save that line so I can get he information from the line below. 到目前为止,我可以将输入到该行的日期与该日期匹配,但是不知道如何保存该行,因此我可以从下面的行中获取他的信息。

f = open("studentinfo.txt")
#ask for date
d = input("Enter the date:")
date = [d]
#check to see if date is avialable
while True:
    line = f.readline().split()
    if line:
        if line == date:
            print(line)
            #save data in here, index etc
    else:
        break
        print("No data available")

How do you save an index of a list while in a 'while' loop. 如何在“ while”循环中保存列表的索引。 Basically I am running through a text file and I want to identify a date, and then afterwards get the information that corresponds to that date which is the line below. 基本上,我正在浏览一个文本文件,我想标识一个日期,然后再获取与该日期相对应的信息,即下面的行。 So far I can match the date entered to the line with that date but don't know how to save that line so I can get he information from the line below. 到目前为止,我可以将输入到该行的日期与该日期匹配,但是不知道如何保存该行,因此我可以从下面的行中获取他的信息。

f = open("studentinfo.txt")
#ask for date
d = input("Enter the date:")
date = [d]
#check to see if date is avialable

for i, line in enumerate(f.readlines()):
    if line:
        if line == date:
            print(line)
            #save data in here, index etc
    else:
        break
        # print("No data available") <-- check indents unreachable code

You have to track the index manually, ie: 您必须手动跟踪索引,即:

i = 0
while True:
    # Do stuff.
    i += 1

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

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