【问题标题】:Getting the position of an item in a list from an input (Python)从输入中获取项目在列表中的位置(Python)
【发布时间】:2016-01-25 21:19:45
【问题描述】:

我有一个包含单词的列表。我想获得用户要求的句子中单词的位置。 (我正在使用python) 例如,如果我有这句话:"Hello world how are you doing today world?" 'World' 出现在第一和第八位置。如果用户想知道单词'world' 在该句子中的位置,它将打印"The word world is in position 1 and 8"。我知道enumerate 方法,但无法让它与输入或elif 语句一起使用。无论单词出现多少次,我都想获取句子中任何单词的位置。

【问题讨论】:

  • word = input("Enter word: ").strip().lower()answer = [i for i,w in enuemrate(sentence.lower().split()) if w==word]
  • @inspectorG4dget 不,介意“?”。
  • @timgeb:不确定我是否关注
  • @inspectorG4dget 您的代码也是我的第一次尝试,但它在“世界”中找不到“世界”?但规范说应该。

标签: python list


【解决方案1】:
sentence = "Hello world how are you doing today world?".lower()
searchword = input("Enter word:  ").lower()

newsentence = ''

for character in sentence:
    if character.islower() or character == ' ': newsentence += character

answer = [position for position, word in enumerate(newsentence.split()) if searchword == word]

print(answer)

【讨论】:

  • 我使用了你的方法,但是它使用了错误的位置。例如 0 应该是 1。我知道为什么会这样。我尝试添加 1 来回答,但这只会导致错误。我想知道您是否知道解决方案?
  • 列表从位置 0 开始。Hello 在“Hello world”中的位置 0。我不会推荐它,但如果有必要,我会将答案更改为下面。 answer = [position + 1 for position, word in enumerate(newsentence.split()) if searchword == word]
【解决方案2】:

您可以使用正则表达式提取单词,然后在列表推导中使用enumerate() 来查找单词的索引:

>>> import re
>>> s =  "Hello world how are you doing today world?"
>>> word = input("Enter a word: ").lower()
Enter a word: world
>>> [i for i, v in enumerate(re.findall(r'\w+', s)) if v == word]
[1, 7]

【讨论】:

    【解决方案3】:

    在您的句子中,"world" 一词出现在位置 1 和 7。

    > sentence = "Hello world how are you doing today world?"
    > word = input("Enter word:  ").lower()
    > answer = [i for i, w in enumerate(sentence.lower().split()) if word in w]
    > answer
    > [1, 7]
    

    无论大小写或标点符号如何,这都会起作用。

    【讨论】:

    • 这也将打印单词是子字符串的单词的位置,例如"worlds".
    • 或者"otherworldly",这些字真的要算吗?
    • 是的。 re 解决方案看起来不错,或者如果 R.McEvoy 不想使用 re,@Michael 解决方案看起来不错。
    【解决方案4】:

    使用re.finditerenumerate

    >>> import re
    >>> s='Hello world how are you doing today world?'
    >>> word='world'
    >>> [i for i, w in enumerate(re.finditer('\w+', s)) if w.group()==word]
    [1, 7]
    

    我们(贪婪地)找到由非单词字符分隔的每个字符序列,对其进行迭代,如果它等于目标单词,则存储索引。

    【讨论】:

      【解决方案5】:
       import re
       s='Hello world how are you doing today world?'
       word='world'
       [i for i, w in enumerate(re.findall('\w+', s)) if w.lower() == word.lower()]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-26
        • 2016-02-27
        • 1970-01-01
        • 2016-12-28
        • 2018-09-21
        • 2012-08-09
        • 1970-01-01
        相关资源
        最近更新 更多