【问题标题】:How do I make words of certain length flip?如何使一定长度的单词翻转?
【发布时间】:2020-05-30 10:23:20
【问题描述】:

所以我正在尝试创建一个程序,它可以接收句子并使长度为 5 或更长的单词反转。目前只是翻转最后一个符合条件的单词,不知道为什么。

userInput = "Hello this is a test sentence"
wordList = userInput.split()

for i in wordList:
    if len(i) >= 5:
        reversedWord = i[::-1]
        print(reversedWord)
        reversedSentence = userInput.replace(i, reversedWord)

print(reversedSentence)

不是输出“olleH,这是一个测试 ecnetnes”,而是输出“你好,这是一个测试 ecnetnes”

【问题讨论】:

  • 你总是用原始字符串来替换。
  • Python有一个函数reversed,这里使用起来可能比i[::-1]更清晰。将i 替换为word 可能也会使事情更清楚。
  • 用有意义的名称 word 替换 i 是个好主意。但是如果你使用reversed,你必须自己重建字符串(例如reversed_word = ''.join(reversed(word)))。
  • 它可能看起来很糟糕,但表明你可以通过加入、拆分和列表理解来做很多事情:print(' '.join([(word if len(word) < 5 else ''.join(reversed(word)) )for word in userInput.split(' ')])) x)
  • @garglblarg 当然显而易见的解决方案是print(' '.join((lambda x: x[::2*(len(word) < 5)-1])(word) for word in sentence.split()))

标签: python python-3.x python-2.7 loops iteration


【解决方案1】:

你不断替换原来的userInput

reversedSentence = userInput
for i in wordList:
    if len(i) >= 5:
        reversedWord = i[::-1]
        print(reversedWord)
        reversedSentence = reversedSentence.replace(i, reversedWord)

您需要继续更新 reversedSentence 变量。

【讨论】:

    【解决方案2】:

    您的代码中的实际错误已经说明,我只想添加一些关于样式的反馈:

    您正在执行以下步骤:

    • 将输入拆分为单词
    • 找到符合您要求的单词 (len(word) > 5)
    • 更改每个字符串的原始字符串

    这是相当不合常规的并且有点不直观(它的性能也很差,因为它会多次操纵您的原始字符串)。我推荐以下算法:

    • 将输入拆分为单词
    • 将符合您要求的单词倒转在该列表中
    • 再次将列表加入一个句子以获取您的字符串

    示例实现:

    user_input = "Hello this is a test sentence"
    processed_words = []
    
    for word in user_input.split():
        if len(word) >= 5:
            word = word[::-1]
        processed_words.append(word)
    
    reversed_sentence = ' '.join(processed_words)
    print(reversed_sentence)
    

    通过使用generator expression 将这个想法更进一步,它可能看起来像这样:

    user_input = "Hello this is a test sentence"
    
    reversed_sentence = ' '.join(
        word[::-1] if len(word) >= 5 else word
        for word in user_input.split())
    
    print(reversed_sentence)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      相关资源
      最近更新 更多