![](/img/trans.png)
[英]Converting "for" loop with nested "for" loop and "If" statement into List Comprehension?
[英]Converting A Nested For Loop Into a List Comprehension
我正在尝试为这个嵌套 for 循环编写一个嵌套列表 comp,但我找不到一个解决方案,它也包含一个跟踪器变量,因此感谢任何帮助。
所以故事是我有一个字典,以单个单词作为键,一个句子列表作为值,我正在访问每个列表,然后访问列表中的每个句子,将其拆分为空格,并将每个句子中的累积标记计数存储在一个新列表,最后重置计数并移动到下一个列表。
# combines the sum of each sentence
l = []
# Tracker variable
sum_len = 0
# For each list in the dictionary values
for cl in word_freq.values():
# For each sentence in the current list
for sen in cl:
# split into tokens and combine the sum of each sentence
sum_len += len(sen.split())
# Append the sum of tokens
l.append(sum_len)
# Reset the variable
sum_len = 0
如果要从字典创建字数列表,可以执行以下操作:
l = [sum(len(sen.split()) for sen in v) for v in word_freq.values()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.