Python 索引()的替代方案

Python 索引()的替代方案,python,Python,因此,对于我的项目,我必须允许用户输入一个句子,然后输入一个单词,找到该单词的所有词组并打印数字。这是我的 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() f

因此,对于我的项目,我必须允许用户输入一个句子,然后输入一个单词,找到该单词的所有词组并打印数字。这是我的

    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")

但它只打印出这个词的第一次出现,很少起作用。有什么解决方案吗?

列表
替换
列表

search1
事件的位置列表:

positions = [idx for idx, el in enumerate(a_list) if el == search1]

您有一个很好的选择,那就是re.finditer:

import re
sen = input("Enter the sentence you would like to break down!")
search = input("Enter the word you want to search")
for match in re.finditer(search, sen):
    print (match.start())

有几条评论提到了将
list
用作变量名的危险。它实际上不是一个保留字,但它是一个内置类型的名称,如果您以后希望使用该类型来构造列表或测试对象的类型,则通过将其用作变量名来隐藏它可能会导致神秘的错误

您发布的代码的一个主要问题是:

search1 = search.upper()
for search1 in list:
第一行将字符串的大写版本
search
保存到名称
search1
。但下一行只是用
列表中的单词来替换;它不执行任何搜索操作。在
for
循环的末尾,
search1
将等于
列表中的最后一项,这就是为什么您的代码在执行
position=list.index(search1)
时没有达到您期望的效果:您告诉它在
列表中查找最后一个单词的位置


你可以使用
.index
来做你想做的事。要查找多个事件,需要使用循环并传递
.index
起始位置。例如

def find_all(wordlist, word):
    result = []
    i = 0
    while True:
        try:
            i = wordlist.index(word, i) + 1
            result.append(i)
        except ValueError:
            return result
但是,在这里使用
.index
并没有什么好处。
.index
以C速度执行扫描,因此它比Python循环中的扫描速度快,但除非扫描的列表很大,否则您可能不会注意到速度差

Tomasz的回答中给出了更简单的方法。这是我在Tomasz写答案时写的一个变体

def ordinal(n):
    k = n % 10
    return "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (k < 4) * k::4])

def find_all(wordlist, word):
    return [i for i, s in enumerate(wordlist, 1) if s == word]

sen = 'this has this like this'
wordlist = sen.upper().split()

words = 'this has that like'
for word in words.split():
    pos = find_all(wordlist, word.upper())
    if pos:
        pos = ', '.join([ordinal(u) for u in pos])
    else:
        pos = 'Not found'
    print('{0}: {1}'.format(word, pos))

ordinal
的代码是“借用”来的。

只是一个注释,您不应该使用变量名
list
,因为它在python中是一个保留字。您正在用自己的变量替换python中默认函数的功能,这可能会导致意外结果。您可以看到。
list
在python中是一个保留关键字,不应该用作变量名。
for loop
enumerate()
可能就是您要查找的。而且@zephyr:
list
并不完全是一个保留字,否则当你试图重新定义它时,你会得到一个语法错误。(请参见如果您尝试为
分配
、在
中分配
、或使用
分配
,会发生什么情况)。但是是的,我们应该避免隐藏内置名称,如
列表
str
dict
,等等。我猜这是一个家庭作业,他们不应该使用内置函数来完成任务。这会打印单词结尾处的值,没有确定的wordOP要求提供一个替代方案,所以我提供了可以说是最好的一个(:@zephyr你不是说只使用内置函数吗?是的,我想内置函数指的是本机python函数,而
re
函数不算作内置函数。撇开术语不谈,它们可能不打算使用
re
this: 1st, 3rd, 5th
has: 2nd
that: Not found
like: 4th