【问题标题】:Python 3.5, Finding user inputted values in a set and displaying themPython 3.5,在集合中查找用户输入的值并显示它们
【发布时间】:2016-11-09 21:07:33
【问题描述】:
from collections import Counter

inp = input("Please enter some text: ")
vowels = set("aeiouAEIOU")

if inp in vowels:
    res = Counter(c for c in inp if c in vowels)
    print (res.most_common())

elif inp not in vowels:
    print("No vowels entered.")

如果在用户输入中找到任何元音,或者如果没有,则打印一条消息,代码旨在输出元音。目前,如果用户输入了多个元音,则代码不起作用,因为它会打印“未输入元音”行。如何纠正这个错误。

【问题讨论】:

    标签: python if-statement input set counter


    【解决方案1】:

    if 块只有在inp 是元音的子串时才会执行。为了检查共享字符,如本例中的元音,您可以使用any

    if any(i in vowels for i in inp):
        ...
    

    或一组交集:

    if vowels.intersection(inp):
        ...
    

    您也可以简单地先构建 Counter 对象,然后测试它是否为空以避免重复输入两次:

    res = Counter(c for c in inp if c in vowels)
    if res:
         print(res.most_common(2)) # specify a parameter to avoid printing everything
    else:
         print("No vowels entered.")
    

    【讨论】:

    • 我想出了完全相同的换行 :) 只是有点晚了
    • @Jean-FrançoisFabre 发生了 :)
    • 不抱怨。今天充满了好问题和赞成的答案:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    • 2018-05-31
    • 2017-10-04
    • 2011-12-11
    • 2016-08-08
    • 1970-01-01
    相关资源
    最近更新 更多