【问题标题】:How to build the variable as an array? [closed]如何将变量构建为数组? [关闭]
【发布时间】:2022-01-03 16:20:53
【问题描述】:

我需要构建一个小程序,用户在输入中键入一些内容,输出将是字母表,没有用户在输入中输入的字母。所以我写了这个:

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
text = input("Please enter any text")
for character in text:
    if character in alphabet:
        alphabet.remove(character)
print(alphabet)

但是现在我需要将变量Alphabet构建为一个数组,使用ascii,而不必手动分配字母,我该怎么做呢?

【问题讨论】:

标签: python arrays python-3.x string variables


【解决方案1】:

试试这个:

from string import ascii_lowercase

text = set(input()) # text = input() is also fine
print([c for c in ascii_lowercase if c not in text])

由于text 可能会很长,所以最好在开始使用if c not in text 之前将其转换为一个集合。如果您不关心时间复杂度,这完全是可选的。

另一种选择(这里您使用的事实是每个字母都可以通过使用ord 转换为字符,并且连续的字母映射到连续的数字):

text = set(input()) # text = input() is also fine
print([chr(i) for i in range(ord('a'), ord('z') + 1) if chr(i) not in text])

多了一个选项(两组之间的差异,后跟一个排序操作):

from string import ascii_lowercase

text = input()
print(sorted(set(ascii_lowercase) - set(text)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2021-05-03
    • 2022-01-23
    • 2022-01-17
    相关资源
    最近更新 更多