【问题标题】:Alternatives to index()index() 的替代品
【发布时间】:2016-03-24 14:22:35
【问题描述】:

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

    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,因为它是python中的保留字。您正在用自己的变量替换 python 中默认函数的功能,这可能会导致意外结果。你可以看到full list here
  • list 是python中的保留关键字,不应用作变量名。
  • for loopenumerate() 可能是您正在寻找的。​​span>
  • @zephyr: list 不完全是保留字,否则当您尝试重新定义它时会收到 SyntaxError。 (看看如果您尝试分配给forinwith 会发生什么)。但是是的,一个应该避免隐藏像liststrdict等内置名称。

标签: python


【解决方案1】:

list 替换为a_list

search1 出现的位置列表:

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

【讨论】:

    【解决方案2】:

    你有一个很好的选择,那就是 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())
    

    【讨论】:

    • 我猜这是一个家庭作业,他们不应该使用内置函数来完成任务。
    • 这会打印单词结尾的值,而不是识别的单词
    • OP 要求提供替代方案,因此我提供了可以说是最好的方案(:
    • @zephyr 你不是说使用内置函数吗?
    • 是的,我想 built-in 将引用本机 python 函数,而 re 函数不会算作内置。撇开术语不谈,它们可能并不打算使用 re
    【解决方案3】:

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

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

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

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


    可以使用.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))
    

    输出

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

    ordinal 的代码是从this answer“借来的”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2012-01-25
      • 2015-08-05
      相关资源
      最近更新 更多