【问题标题】:Why am seeing boolean values in list when performing list comprehension?为什么在执行列表理解时会在列表中看到布尔值?
【发布时间】:2020-11-23 00:50:30
【问题描述】:

遍历文件并搜索文件中出现的几个单词。我写了列表理解,试图将匹配的单词存储在每个阅读行的列表中。

search_strings = ["happy", "sad", "between"]
fio = open("text.txt", encoding="utf-8")
# reading file and trying to find occurences of search_string in text file
for line in fio:
    # first attempt: not what I wanted
    found_list_1 = [word in line for word in search_string]
    # second attempt: what I wanted
    found_list_2 = [word for word in search_string if word in line]
fio.close()

打印出两个构造列表的结果:

found_list_1 打印出来时给我布尔值

[True, False, False]

found_list_2 返回从文件中读取的每一行中找到的字符串。

["happy"]

我试图了解 found_list_1 的列表理解的行为,为什么它返回布尔值而不是匹配的单词?

【问题讨论】:

  • found_list_1 的条目来自您的表达式 word in line,它返回一个布尔值。

标签: python file search list-comprehension


【解决方案1】:
[word in line for word in search_string] # For each word in search_string, does word exist in line?.


[word for word in search_string if word in line] #List all words in search_string that exist in line.

通式:

[<to be listed> for <variable> in <iterable> if <condition>]

其中&lt;to be listed&gt; 通常是:&lt;variable&gt; 本身、包含&lt;variable&gt; 的表达式(例如in)或应用于&lt;variable&gt; 的函数(例如sumlen... )。

【讨论】:

    【解决方案2】:

    为了扩展我的评论,您的 found_list_1 应该是:

    found_list_1 = [word for word in search_string if word in line]
    

    【讨论】:

    • 这是found_list_2。问题是为什么? ;)
    • 我什至没有注意到!答案在我对原始问题的评论中。第一个列表理解是存储 (word in line) 值,这是布尔值。
    • 谢谢。我现在明白了:)
    【解决方案3】:

    found_list_1 为您提供line 中每个word in search_string 出现的布尔信息。

    found_list_2 过滤 search_strings 并仅显示出现在 line 中的 word

    让我们检查一下:

    found_list_1 = [True, False, False]
    search_strings = ["happy", "sad", "between"]
    found_list_2 = ["happy"]
    

    【讨论】:

    • 我现在明白了。谢谢队友:)
    猜你喜欢
    • 1970-01-01
    • 2011-03-01
    • 2018-01-27
    • 1970-01-01
    • 2011-12-22
    • 2015-09-14
    • 2012-10-11
    • 2015-01-21
    相关资源
    最近更新 更多