【发布时间】:2021-06-03 17:06:29
【问题描述】:
我正在学习理解,即列表理解和字典理解。我想使用更多的理解来扩展我的代码。现在,我正在尝试转换这种方法,“解析句子”,我作为网络抓取类的一部分编写,我想将其重写为字典理解。
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 循环是内循环。但我不知道我做错了什么。
【问题讨论】:
-
为什么要添加标签
big-o?似乎是随机的。 -
哦,因为大O不是和算法复杂度有关吗?我试图让我的算法更有效地运行,所以我开始研究 Big-0 符号和时间复杂度
-
Big-O 是关于算法复杂性的,但您的问题似乎不是。您对效率感兴趣这一事实并不会使这成为一个大问题。否则,Stack Overflow 上的几乎每个问题都会被标记。
标签: python list dictionary big-o