首页 > 解决方案 > 修复嵌套 For 循环的字典理解

问题描述

我正在学习理解,即列表理解和字典理解。我想使用更多的理解来扩展我的代码。现在,我正在尝试转换这种方法,“解析句子”,这是我作为网络抓取类的一部分编写的,我想将其重写为字典理解。

def parse_sentences(text_str):
    """
    :param text_str: list of text that needs to be divided by periods
                    at end of sentence.
    :return: list of the individual sentences for every element
            of the list
    """
    # Define list to hold the individual sentences.
    split_text_strings = []
    
    # Loop through each element of the text.
    for i in text_str:
        split_i = i.split('.')
        for j in split_i:
            last = len(split_i) - 1
            if split_i[last] == '':
                split_i.pop(last)
            split_text_strings.append(j)
    
    return split_text_strings

基本上,它采用 ['This is a sentence. 这是一个伟大的句子。','你没有听说过这句话吗?可能是我读过的最好的句子。'] 并返回另一个列表 split_text_strings,其中每个元素都有一个句子,就像这样。['这是一个句子','这是一个伟大的句子','你没听说过这句话','可能是我读过的最好的句子']。这是我尝试将其转换为字典理解

def parse_sentences(text_str):
    """
    :param text_str: list of text that needs to be divided by periods
                    at end of sentence.
    :return: list of the individual sentences for every element
            of the list
    """
    split_text_strings = {(i, j): i.split('.') for i in text_str for j in text_str[text_str.index(i)]}
    return split_text_strings

我知道 '(i, j): i.split('.') for i in text_str' 是外循环,另一个 for 循环是内循环。但我不知道我做错了什么。

标签: pythonlistdictionarybig-o

解决方案


什么不起作用? (1) 第一个函数返回一个列表,而第二个函数返回一个字典。注意函数的描述也是字典。(2) 重复句子或旁边重复句子存在潜在问题。输入['I love StackOverflow.', 'I love StackOverflow']['I love StackOverflow', 'I love StackOverflow']在第一种情况下被处理,但可能会导致字典理解的重复键。这会导致数据丢失。(3)(i, j): i.split('.') for i in text_str for j in text_str[text_str.index(i)]执行以下操作。说,text_str = ['b.c']。那么,i='b.c'j首先迭代'bc',然后j取值'b', '.', 'c'。那么,结果是

{
  ('b.c', 'b'): ['b', 'c'],
  ('b.c', '.'): ['b', 'c'],
  ('b.c', 'c'): ['b', 'c']
}

这不是你想要的。

你想要做什么 我认为你想要的关键如下:(text_str应该称为text_arr,顺便说一句)中字符串的序号和子字符串中句子的序号。例如,['a...', 'b.c']将表示为

{
  (0, 0): 'a',
  (1, 0): 'b',
  (1, 1): 'c'
}

在这种情况下,我们需要确定字符串的顺序。外循环是

(i, ?): ?? for i, string in enumerate(text_str)

我们马上填写问号。我们需要解析每个字符串,因此我们需要考虑string.split('.')并遍历所有句子。这给了我们以下答案

(i, j): sentence for i, string in enumerate(text_str) for j, sentence in enumerate(string.split('.'))

最后,我们需要过滤掉空字符串,如下所示:

(i, j): sentence for i, string in enumerate(text_str) for j, sentence in enumerate(string.split('.')) if sentence

推荐阅读