while 循环出现问题。程序看不到列表的元素
这是任务:使用while循环,if语句和str()函数;遍历列表,如果有100,则用其索引号进行打印。 IE:“索引号有100个:5”,
如果我这样编码 -
lst = [10, 99, 98, 85, 45, 59, 65, 66, 76, 12, 35, 13, 100, 80, 95]
i = 0
while i < len(lst):
if lst[i] == 100:
print("There is a 100 at index no:", str(i))
i += 1
,一切都很好 但是,如果我尝试使用用户输入的列表而不是设置列表,则代码不起作用:
lst = input('Enter your nums:').split(',')
entered_data = list(lst)
i = 0
while i < len(entered_data):
if entered_data[i] == 100:
print("There is a 100 at index no:", str(i))
i += 1
我不明白为什么是这样。请帮忙。
This is the task: Using while loop, if statement and str() function; iterate through the list and if there is a 100, print it with its index number. i.e.: "There is a 100 at index no: 5"
If I code like this -
lst = [10, 99, 98, 85, 45, 59, 65, 66, 76, 12, 35, 13, 100, 80, 95]
i = 0
while i < len(lst):
if lst[i] == 100:
print("There is a 100 at index no:", str(i))
i += 1
, then everything is fine
but if I try using user inputted list instead of a set list the code is not working:
lst = input('Enter your nums:').split(',')
entered_data = list(lst)
i = 0
while i < len(entered_data):
if entered_data[i] == 100:
print("There is a 100 at index no:", str(i))
i += 1
I don't understand why is that so. Please, help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
输入生成一个字符串。
这个字符串,您将其分配在昏迷中,但它仍然是字符串列表。
然后,您应该施放进入的类型。
我用A代替您的时间是实现相同目标的一种更重要的方法。
The input generates a string.
This string, you split it on coma, but it is still a list of strings.
Then you should cast the type of your entry.
I replaced your while with a for that is a more pythonic way to achieve the same goal.
输入元素时,输入函数将输入作为字符串(str),而不是您可能知道的整数。
一个简单的解决方案将将元素投入整数,并完成所有操作。
因此,代码会
注意到,更改的行是您将元素与整数100进行比较的地方。
您还可以打印“
entered_data
”
When you input elements, input function takes the input as string(str), not integers as you may be knowing.
a simple solution would be casting the element into an integer and all is done.
So the code would be like
Note that, the changed line is where you are comparing the element with integer 100.
You can also print the 'entered_data', you will be able to see the single quotes around the single elements(I am using a jupyter notebook)
The code to show the list elements
It's output is