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

时间:2019-12-14 01:24:16

标签: python list indexing element

我有一个已成功读入列表的文件,我有一个循环读取列表的每一行,以查找名为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))

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

如何循环使用索引,并使用索引来跟踪找到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])