Skip to main content
 首页 » 编程设计

python之在 if 语句下将两个 for 循环合并在一起

2025年04月02日21www_RR

我正在尝试将这两个代码合并在一起,以便最后一 block 可以将文本文档“Payments”附加到列表中。对于“付款”的每一行,我希望它位于 myList 的列表中,因此它看起来像这样:

myList = [['E1234','12/09/14','440','A','0']['E3431','10/01/12','320','N','120']['E0987','04/12/16','342','A','137']] 

我希望能够创建最终代码以提示用户输入客户编号,然后通过 myList 搜索客户编号并在屏幕上显示客户的所有信息。

这是两个程序中的第一个。它是最终代码的“ Backbone ”。我们称之为 A:

print("Option A: Show a record\nOption Q: Quit") 
decision = input("Enter A or Q: ") 
 
if decision == "A" or decision == "a": 
    myFile = open("Payments.txt") 
    customer_number = input("Enter a customer number to view their details: ") 
    record = myFile.readlines() 
    for line in record: 
        if customer_number in line: 
            print(line) 
    myFile.close() 
 
elif decision == "Q" or "q": 
    exit 

这是第二段代码。让我们称之为 B:

myFile = open("Payments.txt") 
myList = [] 
for item in myFile: 
    print(item.strip()) 
    myList.append(item.strip().split(',')) 
myFile.close() 
print(myList) 

我想将 B 插入到 if 语句中:if decision == "A"or decision == "a":。

我对 for 循环感到困惑,因为 A 和 B 中有一个 for 循环,这两者对于最终代码都至关重要。我无法在不中断任何一个 for 循环的情况下将 B 放入 A。

print("Option A: Show a record\nOption Q: Quit") 
decision = input("Enter A or Q: ") 
myList = [] 
 
if decision == "A" or decision == "a": 
    myFile = open("Payments.txt") 
    customer_number = input("Enter a customer number to view their details: ") 
    record = myFile.readlines() 
    for line in record: 
        for item in myFile: 
            print(item.strip()) 
            myList.append(item.strip().split(',')) 
            print(myList) 
        if customer_number in line: 
            print(line) 
    myFile.close() 
 
elif decision == "Q" or "q": 
    exit 

它显示客户编号来自的行,但不打印列表。

更新

我希望能够分别打印每一行的单个数据:

Customer number: E1234 
Date of payment: 12/09/14 
Payment amount: £440 
Paid amount: £0 

请您参考如下方法:

在您的评论中,您提到您需要附加到一个列表,所以我修改了我的脚本以包含它,但您当前的答案是将 A 和 B 部分分开,但您必须将它们组合起来。

逻辑是,如果 customer_number 存在于一行中,那么您将附加到列表并使用循环遍历列表以打印您想要的内容。您的解决方案是打印整行客户详细信息,并每隔一行打印一次。

print("Option A: Show a record\nOption Q: Quit") 
decision = input("Enter A or Q: ").lower() 
myList = [] 
 
if decision == "a": 
    myFile = open("Payments.txt") 
    customer_number = input("Enter a customer number to view their details: ") 
    record = myFile.readlines() 
    for line in record: 
        if customer_number in line: 
            myList.append(line.strip().replace("'","").split(',')) 
            for info in myList: 
                print("Customer number: ", info[0]) 
                print("Date of payment: ", info[1]) 
                print("Payment Amount: ", info[2]) 
                print("Paid Amount: ", info[4]) 
    myFile.close() 
 
elif decision == "q": 
    exit() 

这是输出: