【发布时间】:2017-06-23 16:05:46
【问题描述】:
我有以下代码:
def main():
list=["chocolate", "jelly", "biscuits"]
eat=input("What do you wanna eat?")
for i in list:
if list.index(eat)==eat:
break
else:
break
print("We have that in tray:", list.index(eat))
main()
在 VB.Net 中,这将在 For 循环中很容易地工作,这将是执行此操作的惯用方式。为什么不在这里?此外,这不是 stackoverflow 上另一个问题的重复,其中用户提供了做类似事情的替代方法/pythonic 建议。
出于教学目的,我需要使用 for 循环,并更正上面给出的结构。
如果用户输入的内容不是列表中的内容,我如何添加将打印“该项目不在列表中”的条件逻辑。我正在寻找最简单的原始代码修复方法。
我确实尝试了以下操作,但出现了逻辑错误。有了解决方案。
尝试#1:
def main():
list=["chocolate", "jelly", "biscuits"]
eat=input("What do you wanna eat?")
for i in list:
if list.index(eat)==eat:
break
else:
print("that is not in the list")
print("We have that in tray:", list.index(eat))
main()
错误:
>>>
What do you wanna eat?jelly
that is not in the list
that is not in the list
that is not in the list
We have that in tray: 1
>>>
试试 2
def main():
list=["chocolate", "jelly", "biscuits"]
eat=input("What do you wanna eat?")
for i in list:
if list.index(eat)==eat:
break
else:
break
print("that is not in the list")
print("We have that in tray:", list.index(eat))
main()
错误:
>>>
What do you wanna eat?jelly
that is not in the list
We have that in tray: 1
>>>
尝试#3:
def main():
list=["chocolate", "jelly", "biscuits"]
eat=input("What do you wanna eat?")
for i in list:
if list.index(eat)==eat:
break
elif list.index(eat)!=eat:
print("that is not in the list")
print("We have that in tray:", list.index(eat))
main()
错误:
>>>
What do you wanna eat?jelly
that is not in the list
that is not in the list
that is not in the list
We have that in tray: 1
>>>
【问题讨论】:
-
你说的最简单的修复是什么意思?您如何衡量简单性?
-
我的意思是,我不希望人们建议使用字典、lambda 或者我需要摆脱 for 循环!。我只希望我放在那里的代码得到修复和评论。因此,在 for 循环中添加了一条打印行,表示“不在列表中”。我希望它使用 FOR 循环修复 - 不是没有。这是关键
-
...或枚举!
-
知道了,答案已更新
-
list.index(x)返回列表中第一个值为 x 的项目的索引。如果没有这样的项目是错误的。您试图将此 index 与您给出的值进行比较,吃。
标签: python list python-3.x loops for-loop