【问题标题】:Python Zybooks LAB 9.6 - Contact ListPython Zybooks LAB 9.6 - 联系人列表
【发布时间】:2022-11-24 16:16:40
【问题描述】:

再一次,我不明白我一直遇到的错误。这是我的代码:

s = input()

name = input()

splits = s.split(" ")

i = 0

for i in range(len(splits)):

   if(splits[i] == name):

       break

print(splits[i+1])

这是错误:

Traceback (most recent call last):
  File "main.py", line 15, in <module>
    print(splits[i+1])
IndexError: list index out of range

我不确定为什么 [i+1] 返回超出范围。这次我搞砸了什么?我提前感谢你的帮助,因为我没有从我的导师或助教那里得到太多指导。你们在这里摇滚!

编辑:很抱歉我没有包含期望的结果。

输入是: 乔,123-5432 琳达,983-4123 弗兰克,867-5309

坦率

输出应该是: 867-5309

【问题讨论】:

  • 你试过调试你的代码吗?试着一步一步地运行你的代码,即使把它写在一张纸上也可以,给定一个输入,检查你的代码是否按照你的预期运行。你应该很容易发现你的问题恕我直言。

标签: python


【解决方案1】:
s = 'Hello'
name = 'Goodbye'
splits = s.split() # default value is a single space ['Hello'] - notice the single value

for i in range(1): # because splits has a single item in the list
    if 'Hello' == 'Goodbye':
        break
    
print(splits[i+1]) # this will not work because splits has a single index = 0


# same as

s = [0,1]
print(s[2])

我建议您在 StackOverflow 上提问时提出所需的输出,以便其他人更好地理解您的问题。

此外,正如 Hossein 在评论中提到的那样,请尝试在代码的每一行中使用 print() 以查看是否得到了预期的结果。

【讨论】:

  • 谢谢您的答复。我进行了编辑以包含输入和所需的输出,但仍然遇到“索引超出范围”错误。
猜你喜欢
  • 2022-06-19
  • 1970-01-01
  • 1970-01-01
  • 2022-11-21
  • 2011-05-16
  • 2018-07-16
  • 2010-12-26
  • 1970-01-01
  • 2015-12-21
相关资源
最近更新 更多