【发布时间】:2016-04-27 20:21:15
【问题描述】:
我正在尝试将这两个代码合并在一起,以便最后一块可以将文本文档“付款”附加到列表中。对于每一行“付款”,我希望它在myList 的列表中,所以它看起来像这样:
myList = [['E1234','12/09/14','440','A','0']['E3431','10/01/12','320','N','120']['E0987','04/12/16','342','A','137']]
我希望能够创建最终代码以提示用户输入客户编号,然后通过myList 搜索客户编号并在屏幕上显示客户的所有信息。
这是两个程序中的第一个。它是最终代码的“主干”。我们称它为 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)
我想在 if 语句中插入 B:if decision == "A" or decision == "a":。
我对 for 循环感到困惑,因为 A 和 B 中有一个 for 循环,这两个循环对于最终代码都很重要。我无法将 B 放入 A 而不破坏任何一个 for 循环。
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 会做什么?只需打印 Payments.txt 的内容?
-
B 将 Payments.txt 的每一行添加到 myList 中的单个列表中。我希望 B 在 A 中的 if 语句中,因此它将 Payments 附加到 myList,在列表中找到 customer_number 并显示该特定行
-
所以这样做的全部目的是显示包含 customer_number 的行?为什么还要打扰
myList? -
规则要求在此作业中使用此代码中的列表。抱歉,我之前没有解释过。
-
好的,我修改了我的解决方案来解决这个问题并做你想做的事情:) 你在正确的轨道上,但你没有打印正确的值
标签: python loops python-3.x split strip