[英]Why is this giving me “list index out of range”? I'm trying to find names in a list and names can be two words long or more
_ID = "000001234"
f = open("Players.txt", "r")
allLines = f.readlines()
nameList = [[] for i in range(1,len(allLines))]
for i in range(0,len(allLines)):
splitLine = allLines[i].split()
l = len(splitLine)
for name in range(1,l-3):
nameList[i].append(splitLine[name])
#print(nameList[i])
for i in range(0, len(allLines)):
splitLine = allLines[i].split()
if splitLine[0] == _ID:
print(nameList[i])
break
f.close()
Data: 数据:
Player ID Player Name Age Height(cm) Weight(kg)
000000001 Aaron Appindangoye 26 183 84.8
000000002 Aaron Cresswell 28 170 66.2
000000003 Aaron Doran 26 170 73.9
000000004 Aaron Galindo 36 183 89.8
000000005 Aaron Hughes 38 183 69.9
000000006 Aaron Hunt 31 183 73.0
Your nameList
has a smaller length than a length of allLines
: 您nameList
比长度更小的长度allLines
:
>>> len(allLines)
>>> 7
however, 然而,
>>> len(nameList)
>>> 6
try nameList = [[] for i in range(0,len(allLines))]
尝试nameList = [[] for i in range(0,len(allLines))]
_ID = "000001234"
f = open("Players.txt", "r")
allLines = f.readlines()
nameList = [[] for i in range(0,len(allLines))]
for i in range(1,len(allLines)):
splitLine = allLines[i].split()
l = len(splitLine)
for name in range(1,l-3):
nameList[i].append(splitLine[name])
#print(nameList[i])
for i in range(0, len(allLines)):
splitLine = allLines[i].split()
if splitLine[0] == _ID:
print(nameList[i])
break
f.close()
nameList = [ii for ii in nameList[1:]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.