【问题标题】:Finding the first occurrence of a character in a list查找列表中第一次出现的字符
【发布时间】:2021-08-14 00:54:16
【问题描述】:

我想要一个输入行数的代码(计算空行数),然后是行本身,然后是我要查找的单词,最后是第一次出现一个字符的位置。请不要imports。

我有这个 rn:

lines = int(input())
phrases = []

for i in range(lines):
  phrase = str(input())
  phrase = phrase.replace(',','')
  phrase = phrase.replace('!','')
  phrase = phrase.replace('.','')
  phrase = phrase.replace(';','')
  phrase = phrase.replace(':','')
  phrase = phrase.replace('?','')
  phrase = phrase.replace(' ','')
  phrase = phrase.lower()
  phrases.append(phrase)

word = str(input())

所以输入会是这样的:

6  
I have a computer  

Hello world    
Please help  
Dammit code  
I wish I finished this today  
happy   

我希望结果是这样的:

Word founded  
h: word 2, letter 1  
a: word 3, letter 1  
p: word 4, letter 4
p: word 7, letter 1  
y: word 16, letter 5

不能和最后一个单词同一个字。
如果没有发生这种情况,请打印:

Word not founded

【问题讨论】:

  • 你有什么问题?请使用tour,阅读what's on-topic hereHow to Askquestion checklist。您应该 edit 您的问题包括实际输出,以及您的代码如何未能满足您的期望。欢迎使用 Stack Overflow!
  • 空的算还是不算?
  • 是的,它们都被计算在内,我放了 5 行,但它是 6 行,对不起
  • 你没有在这段代码中调用get_index_position
  • 请编辑您的问题并提供可运行的minimal reproducible example

标签: python list find-occurrences


【解决方案1】:

可能是这样的:

lines = int(input())
words = []

for i in range(lines):
    phrase = input().lower()
    if phrase:
        words.extend(phrase.split(' '))

search_word = input()
output_rows = []
word_found = True

for i, word in enumerate(words):
    if search_word[0] in word:
        output_rows.append(f'{search_word[0]}: word {i+1}, letter {word.index(search_word[0])+1}')
        search_word = search_word[1:]
        if not search_word:
            break
else:
    print("Word not found")
    word_found = False

if word_found:
    print("Word found")
    print('\n'.join(output_rows))

【讨论】:

  • 唯一的缺失点是显示“Word not found”。
  • @ra10121416 究竟是什么意思?谢谢!
  • 就像,如果不是所有的字符都成立,那么它应该打印“Word not found”。
  • 例如:2 'hello world' 'bye world' 'halo' 它包含“h”但不包含“a”,因此应该打印“Word not found”。
  • @ra10121416 将其更改为打印“找到单词”和“未找到单词”
【解决方案2】:

您可以尝试使用list.extend() 方法:

import re

lines = int(input("How many lines? >>> "))
words = []

for _ in range(lines):
    text = input(">>> ").lower()
    words.extend(re.findall(r'\b\S+\b', text))

word = input("Input word >>> ")
i = 0
output = []
for index, w in enumerate(words):
    for letter in word[i:]:
        if letter in w:
            output.append(f"{letter}: w {index + 1}, l {w.index(letter) + 1}")
            i += 1
            break
    else:
        print("Word not founded.")
        break
else:
    print("Word founded.")
    print("\n.join(output)")

【讨论】:

  • 非常感谢!!正如我在问题中提到的那样,当您找到单词的所有字母时,它唯一缺少的是它不会打印“Wordfounded”。以及不是所有角色都成立时的“Word not found”。例如:2 'hello world' 'bye world' 'halo' 包含“h”但不包含“a”,所以应该打印“Word not found”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多