索引()

2024-10-04 01:27:26 发布

您现在位置: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()
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")

但它只会打印出这个词的第一次出现,几乎不起作用。有什么解决办法吗?在


Tags: theininputsearchifposition单词sentence
3条回答

list替换为a_list。在

search1事件的位置列表:

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

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

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

search1 = search.upper()
for search1 in list:

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


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

^{pr2}$

然而,在这里使用.index并没有什么好处。.index以C速度执行扫描,因此它比在Python循环中扫描要快,但是除非您要扫描的列表很大,否则您可能不会注意到太多的速度差异。在

托马斯兹的回答给出了更简单的方法。这是我在托马斯写答案时写的一个变体。在

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

输出

this: 1st, 3rd, 5th
has: 2nd
that: Not found
like: 4th      

ordinal的代码是从this answer借来的。在

你有一个很好的选择芬代尔公司名称:

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

相关问题 更多 >