python - 嵌套 for 和 if 在列表推导中

标签 python python-3.x list python-2.7 list-comprehension

我有以下代码,其中有 for 和 if 可选。

lines = ['apple berry Citrus ', 34, 4.46, 'Audi Apple ']

corpus = [ ]

for line in lines:

    # Check if the element is string and proceed
    if isinstance(line, str):

        # Split the element and check if first character is upper case
        for word in line.split():
            if word[0].isupper():
                
                # Append the word to corpus result
                corpus.append(word)
print(corpus)
# Output : ['Citrus', 'Audi', 'Apple']

我试图在列表理解中做到这一点,但失败了。我试过如下。

# corpus = [  word if word[0].isupper() for word in line.split()  for line in lines if isinstance(line, str)]

我如何在列表理解中实现这一点?

最佳答案

以下将起作用:

corpus = [
    word for line in lines if isinstance(line, str) 
         for word in line.split() if word[0].isupper()
]

嵌套推导中的作用域一开始可能会令人困惑,但您会注意到 forif 的顺序与嵌套循环中的顺序相同。

关于python - 嵌套 for 和 if 在列表推导中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65829248/

相关文章:

python - 从标记中获取子字符串以及标记之后的下一个 200 个字符

arrays - 作业中的 Perl 'context'

python如何在嵌套列表中搜索项目

python - urlopen 是否被延迟评估?

python - pygame中的旋转

Python语音识别很慢

python - 了解Keras的ImageDataGenerator类中的 `width_shift_range`和 `height_shift_range`参数

python-3.x - 加速 agg 并加入十亿记录的 Pandas 表

r - 如何遍历多个模型以放入 R 中的列表

java - 如何修复由 : java. lang.UnsupportedOperationException 引起的并发.ExecutionException