【问题标题】:Python 3 : empty list returned instead of list of words starting with vowel using comprehensionPython 3:使用理解返回空列表而不是以元音开头的单词列表
【发布时间】:2020-10-25 04:00:39
【问题描述】:

当我最近开始学习 python 3 时,我遇到了 Comprehensions,这真的让我很感兴趣,我尝试将一些现有的循环程序转换为带有理解的循环。我一直没有成功地试图让其中一个程序以理解的方式运行。如果单词以元音开头,它会从输入的字符串列表中返回单词列表。

下面给出了可以运行但没有使用 Python 3.0 解析的旧程序。

output_list= []
list_vowel = ['a','e','i','o','u']
for word in input_list: 
    if word[0] in list_vowel:
        output_list.append(word)
print(output_list) 

当我尝试使用理解编写相同的程序时,我每次运行代码时都会得到空列表 [],无论 i/p 列表是否为 ['a','e','i','o','u'] or ["aeiou"] etc

下面给出了使用理解的代码

import ast,sys
input_str = sys.stdin.read()
input_list = ast.literal_eval(input_str)

output_list = []
list_vowel = ["aeiou"]
output_list = [ x for x in input_list if x[0] in list_vowel ]
# for i in list_vowel if x[0] == list_vowel[i]]
print(output_list) 

我做错了什么? 或者如果存在我们不能使用 python 推导的情况?

【问题讨论】:

    标签: python-3.x list-comprehension


    【解决方案1】:

    如果您将list_vowel = ["aeiou"] 替换为list_vowel = "aeiou"list_vowel = ['a','e','i','o','u'],则该代码有效。 "a" 不在 ["aeiou"] 中,因为该可迭代对象中的唯一元素是 "aeiou"

    【讨论】:

    • 我在 jupyter 中重试了 ``` list_vowel = "aeiou" & list_vowel = ['a','e','i','o','u'] ``` 但是得到了以下错误消息``` Traceback(最近一次调用最后):文件“”,第 3 行,在 input_list = ast.literal_eval(input_str) ..文件“/home/ abhi/anaconda3/lib/python3.7/ast.py”,第 35 行,在解析中返回编译(源,文件名,模式,PyCF_ONLY_AST)文件“”,行未知 ^ SyntaxError:解析时意外 EOF ```
    • 在不同的编译器中工作。谢谢,jupyter notebook 可能有问题。
    猜你喜欢
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 2017-04-01
    • 2017-02-27
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多