【问题标题】:Trying to print list element after reading each line for a string在读取字符串的每一行后尝试打印列表元素
【发布时间】:2020-04-07 10:31:11
【问题描述】:

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

【问题讨论】:

    标签: python list indexing element


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 嘿,这很整洁 :)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2014-11-30
      • 2021-02-24
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多