我试图打印变量'Number',但出现错误。在
'类型错误:列表索引必须是整数,而不是元组'
我不明白?什么是元组?我如何解决这个问题? 如何将文本文件中的行号赋给变量?在
def CheckDatabase():
print ("====Check Database===== \nA)Would you like to check details? \nB)Check if they are a member?")
TC = input(": ")
if TC == "A" or TC == "a":
NameDetail = input ("Please enter the name you would like to check the details of.\nThis will only work if they are a member\n: ")
with open('Name.txt') as ND:
for number, line in enumerate(ND, 1):
if (str(NameDetail)) in line:
Number = number, line in enumerate(ND, 1)
print ("\nName = ", NameDetail)
A = open("Address.txt", "r")
AData =[line.rstrip() for line in A.readlines()]
print ("Address = ",(AData[Number]))
HN = open("Home Number.txt", "r")
HNData =[line.rstrip() for line in HN.readlines()]
print ("Home Number = ",(HNData[Number]))
MN = open("Mobile Number.txt", "r")
MNData =[line.rstrip() for line in MN.readlines()]
print ("Mobile Number = ",(MNData[Number]))
EAS = open("Email Address.txt", "r")
EAData =[line.rstrip() for line in EAS.readlines()]
print ("Email Address = ",(EAData[Number]))
MDND = open("Email Address.txt", "r")
MDNData =[line.rstrip() for line in MDND.readlines()]
print ("Medical/Dietry Needs = ",(MDNData[Number]))
else:
print ("Person not found!")
编辑:
^{pr2}$编辑2: 名称.txt公司名称:
Sagar Bharadia
在地址.txt在
8 John Road
家数字.txt在
02089563524
移动数字.txt在
02045745854
医学营养学需求.txt在
None
编辑3:
SVA of UK Database
A)Check Database
B)Add to Database
C)Exit Program
: A
====Check Database=====
A)Would you like to check details?
B)Check if they are a member?
: A
Please enter the name you would like to check the details of.
This will only work if they are a member
: Sagar Bharadia
Name = Sagar Bharadia
1
Traceback (most recent call last):
File "H:\SVA UK PROGRAM\SVA of UK.py", line 126, in <module>
Main()
File "H:\SVA UK PROGRAM\SVA of UK.py", line 114, in Main
CheckDatabase()
File "H:\SVA UK PROGRAM\SVA of UK.py", line 74, in CheckDatabase
print ("Address = ",(AData[Number]))
IndexError: list index out of range
>>>
这一行:
将两个值赋给Number这将产生一个元组。在
你可以这样做:
^{pr2}$这将导致Number成为单个值,而不再是元组。在
当您执行
Number = number, line in enumerate(ND, 1)
时,您将Number
定义为元组。您已经用for
循环创建了number, line in enumerate(ND, 1)
。为什么不直接用它呢?i、 e.AData[number]
。在仅举个例子,这就是您将
Number
设置为:它是一个元组,包含来自}的值(一个布尔表达式,要么在那里,要么不在那里)。在
for
循环的number
和{您还有其他几个问题:
1
开始,而不是0
,方法是将1
提供给enumerate
。在python中,列表索引从0
开始。因此,如果一个列表的长度是1
,那么[1]
处的子索引实际上是越界的。您应该做enumerate(ND)
,而不是从0
开始。在.close()
您的文件open()
,或者像处理第一个文件一样使用with
/as
。在Email Address.txt
两次。。。你是故意的吗?在元组是一种“列表”。见文件:
http://docs.python.org/release/1.5.1p1/tut/tuples.html
您可能正在为var编号指定2个或更多个值
相关问题 更多 >
编程相关推荐