我有两个列表如下
tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]
我想从entries
中提取条目,当它们在tags
中时:
result = []
for tag in tags:
for entry in entries:
if tag in entry:
result.extend(entry)
我怎样才能写两个循环作为单行列表理解?
记住这一点的最好方法是,列表理解中 for 循环的顺序基于它们在传统循环方法中出现的顺序。最外层的循环首先出现,然后是内部循环。
所以,等效列表的理解是:
[entry for tag in tags for entry in entries if tag in entry]
一般来说,if-else
语句在第一个 for 循环之前,如果你只有一个if
语句,它会在最后。例如,如果你想添加一个空列表,如果tag
不在条目中,你会这样做:
[entry if tag in entry else [] for tag in tags for entry in entries]
这应该做到这一点:
[entry for tag in tags for entry in entries if tag in entry]
适当的 LC 将是
[entry for tag in tags for entry in entries if tag in entry]
LC 中循环的顺序类似于嵌套循环中的顺序,if 语句转到末尾,条件表达式转到开头,类似于
[a if a else b for a in sequence]
看演示-
>>> tags = [u'man', u'you', u'are', u'awesome']
>>> entries = [[u'man', u'thats'],[ u'right',u'awesome']]
>>> [entry for tag in tags for entry in entries if tag in entry]
[[u'man', u'thats'], [u'right', u'awesome']]
>>> result = []
for tag in tags:
for entry in entries:
if tag in entry:
result.append(entry)
>>> result
[[u'man', u'thats'], [u'right', u'awesome']]
编辑-由于您需要将结果展平,因此可以使用类似的列表理解,然后展平结果。
>>> result = [entry for tag in tags for entry in entries if tag in entry]
>>> from itertools import chain
>>> list(chain.from_iterable(result))
[u'man', u'thats', u'right', u'awesome']
把这些加在一起,你就可以
>>> list(chain.from_iterable(entry for tag in tags for entry in entries if tag in entry))
[u'man', u'thats', u'right', u'awesome']
您在这里使用生成器表达式而不是列表理解。(也完全匹配 79 个字符的限制(没有list
调用))
在理解中,嵌套列表迭代应该遵循与循环的等效 imbricated 相同的顺序。
为了理解,我们将以 NLP 中的一个简单示例为例。您希望从句子列表中创建所有单词的列表,其中每个句子都是单词列表。
>>> list_of_sentences = [['The','cat','chases', 'the', 'mouse','.'],['The','dog','barks','.']]
>>> all_words = [word for sentence in list_of_sentences for word in sentence]
>>> all_words
['The', 'cat', 'chases', 'the', 'mouse', '.', 'The', 'dog', 'barks', '.']
要删除重复的单词,可以使用 set {} 而不是 list []
>>> all_unique_words = list({word for sentence in list_of_sentences for word in sentence}]
>>> all_unique_words
['.', 'dog', 'the', 'chase', 'barks', 'mouse', 'The', 'cat']
or applylist(set(all_words))
>>> all_unique_words = list(set(all_words))
['.', 'dog', 'the', 'chases', 'barks', 'mouse', 'The', 'cat']
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(67条)