在读取字符串的每一行后尝试打印列表元素

Trying to print list element after reading each line for a string

我有一个已成功读入列表的文件,我有一个循环读取该列表的每一行以查找名为 customerID 的变量,它只是一个由 4 个数字组成的字符串。

我试图让 if 语句打印找到 customer ID 的列表的索引,以及该行(索引)的内容。

def searchAccount(yourID):

    global idLocation
    global customerlist
    with open("customers.txt", "r") as f:
        customerlist = [line.strip() for line in f]


    IDExists = False
    for line in customerlist: 
        if yourID in line: 
           IDExists = True 

           break

        else: 
            IDExists = False 

    if IDExists == True: 
        print(customerlist.index(yourID))

使用索引循环,并使用索引跟踪找到 ID 的位置如何?

def searchAccount(yourID):

    global idLocation # What's this for?
    global customerlist
    with open("customers.txt", "r") as f:
        customerlist = [line.strip() for line in f]


    index = -1
    for i in range(len(customerlist)): 
        if yourID in customerlist[i]: 
           index = i
           break

    if index > -1:
        print('Index was {}'.format(i))
        print(customerlist[i])

不是使用 range(len(customerlist)) 然后 customerlist[i] 来获取一行,您可以使用 enumerate() 来获取行的索引和行本身。

def search_account(your_id):
    with open("customers.txt") as txt:
        for i, line in enumerate(txt):
            if your_id in line.strip():
                print(i, line)
                break