如果对象不在列表中,则搜索列表中的下一项

2024-03-28 19:31:06 发布

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

我正在尝试学习如何搜索csv文件。在本例中,我已经了解了如何搜索特定列(出生日期)以及如何在该列中搜索索引以获得出生年份

我可以搜索超过一个特定的年份-例如,输入45将给我所有1945年或1945年以后出生的人,但我卡住了一点是,如果我输入的年份不是特别在csv/列表中,我会得到一个错误,说这一年不在列表中(它不是)

我想做的是遍历列中的年份,直到找到列表中的下一个年份,然后打印任何大于该年份的内容

我试过几次迭代,但我的大脑终于停了下来。这是我目前的代码

data=[]
with open("users.csv") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        data.append(row)
print(data)

lookup = input("Please enter a year of birth to start at (eg 67): ")

#lookupint = int(lookup)


#searching column 3 eg [3]
#but also searching index 6-8 in column 3
#eg [6:8] being the year of birth within the DOB field
col3 = [x[3][6:8] for x in data]

#just to check if col3 is showing the right data
print(col3)
print ("test3")



#looks in column 3 for 'lookup' which is a string
#in the table
if lookup in col3: #can get rid of this
    output = col3.index(lookup)
    print (col3.index(lookup))
    print("test2")

    for k in range (0, len(col3)):
        #looks for data that is equal or greater than YOB
        if col3[k] >= lookup:
           print(data[k])

提前谢谢


Tags: ofcsvthein列表fordataindex