因此,对于我的项目,我必须允许用户输入一个句子,然后输入一个单词,然后找到这个单词的所有位置并打印数字。这是我所拥有的
found = 0
sen = input("Enter the sentence you would like to break down!")
sen1 = sen.upper()
list = sen1.split()
search=input("Enter the word you want to search")
search1 = search.upper()
for search1 in list:
found = found + 1
position=list.index(search1)
if position == 0:
print("First word in the sentence")
if position == 1:
print("Second word in the sentence")
if position == 2:
print("Third word in the sentence")
if position == 3:
print("Fourth word in the sentence")
if position == 4:
print("Fifth word in the sentence")
if position == 5:
print("6th word in the sentence")
else:
position1 = position + 1
print(position1, "th word in the sentence")
但它只会打印出这个词的第一次出现,几乎不起作用。有什么解决办法吗?在
将
list
替换为a_list
。在search1
事件的位置列表:一些评论提到了使用
list
作为变量名的危险。它实际上不是一个保留字,但它是一个内置类型的名称,如果您以后希望使用此类型来构造列表或测试对象的类型,那么使用它作为变量名来隐藏它可能会导致神秘的错误。在您发布的代码的一个主要问题是:
第一行将字符串
search
的大写版本保存到名称search1
。但是下一行只是用list
中的单词来删除它;它不执行任何搜索操作。在for
循环的末尾,search1
将等于list
中的最后一个项目,这就是为什么您的代码在执行position=list.index(search1)
时没有按照您的预期执行:您告诉它查找list
中最后一个单词的位置。在你可以用
^{pr2}$.index
做你想做的事。要找到多个引用,需要使用循环并传递.index
一个起始位置。例如然而,在这里使用
.index
并没有什么好处。.index
以C速度执行扫描,因此它比在Python循环中扫描要快,但是除非您要扫描的列表很大,否则您可能不会注意到太多的速度差异。在托马斯兹的回答给出了更简单的方法。这是我在托马斯写答案时写的一个变体。在
输出
ordinal
的代码是从this answer借来的。在你有一个很好的选择芬代尔公司名称:
相关问题 更多 >
编程相关推荐