繁体   English   中英

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

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

如何在“ while”循环中保存列表的索引?

基本上,我正在浏览一个文本文件,我想标识一个日期,然后再获取与该日期相对应的信息,即下面的行。 到目前为止,我可以将输入到该行的日期与该日期匹配,但是不知道如何保存该行,因此我可以从下面的行中获取他的信息。

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")

如何在“ while”循环中保存列表的索引。 基本上,我正在浏览一个文本文件,我想标识一个日期,然后再获取与该日期相对应的信息,即下面的行。 到目前为止,我可以将输入到该行的日期与该日期匹配,但是不知道如何保存该行,因此我可以从下面的行中获取他的信息。

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

您必须手动跟踪索引,即:

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

暂无
暂无

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

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