【问题标题】:How to stop programs printing out in alphabetical order如何停止按字母顺序打印的程序
【发布时间】:2018-06-07 17:10:52
【问题描述】:

所以,我正在开发一个程序,将输入文本转换为 Discords region_indicator 表情符号,但问题是,如果输入诸如“cab”之类的单词,则输出将返回为“abc”。有没有办法改变程序,以便在输入单词时不按字母顺序排序。 (出于测试目的,我只编写了前 3 个字母。用 Python IDLE 3.5 编码)

import sys
sentence = input("Enter a sentence:")
sentenceLower = sentence.lower()
sentenceList = list(sentenceLower)
sentenceListLength = len(sentenceList)
while sentenceListLength > 0:
    if "a" in sentence:
        sys.stdout.write(":regional_indicator_a:")
        sentenceListLength = sentenceListLength - 1
    if "b" in sentence:
        sys.stdout.write(":regional_indicator_b:")
        sentenceListLength = sentenceListLength - 1
    if "c" in sentence:
        sys.stdout.write(":regional_indicator_c:")
        sentenceListLength = sentenceListLength - 1

简而言之,程序接收一个句子,检查该句子中是否出现字母,然后打印出要复制并粘贴到 Discord 中的文本。

【问题讨论】:

  • 我不确定我是否理解您要执行的操作,但我认为您可能希望遍历句子中的字符,而不是查找句子中的字符。
  • 与我能在短时间内想到的最不有效的方法相比,这是一种效率较低的方法。

标签: python list output


【解决方案1】:

你需要遍历句子中的字符,而不是遍历字符数。

for c in sentence:
    if c == "a":
       sys.stdout.write(":regional_indicator_a:")
    elif c == "b":
        sys.stdout.write(":regional_indicator_b:")
    elif c == "c":
        sys.stdout.write(":regional_indicator_c:")

你所做的只是检查字符串中是否存在一个字符,所以它会给你乱序的字母。

【讨论】:

  • 我喜欢您回答确切问题的方式,但没有解决多个 if 的美学和低效率问题。 +1
  • 不过你至少切换到了elif
  • 感谢您的帮助,这就是问题所在。完全忘记了 elif 语句,我觉得有点愚蠢 xD
【解决方案2】:

一种方法是

import sys
sentence = input("Enter a sentence:")
sentenceLower = sentence.lower()
sentenceListLength = len(sentenceLower)
for i in range(sentenceListLength) :
    c = sentenceLower[i]
    if ( ("a" <= c) and (c <= "z") ) :
        sys.stdout.write(":regional_indicator_"+c+":")
    else :
        # Do your stuff
        pass

你也可以遍历字符

for c in sentenceLower :

而不是

for i in range(sentenceListLength) :
    c = sentenceLower[i]

(它通常被认为更 Pythonic)。使用整数索引有时更灵活/通用(取决于您的情况)。

【讨论】:

猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-18
  • 2020-04-01
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
相关资源
最近更新 更多