如何在列表理解python框架两个for循环 [英] How to frame two for loops in list comprehension python

查看:119
本文介绍了如何在列表理解python框架两个for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个名单如下

  tags = [u'man',u'you',u'are' ,u'awesome'] 
entries = [[u'man',u'thats'],[u'right',u'awesome']]

我想从条目中提取条目,当它们位于 tags

  result = [] 

用于标签的标签:
输入条目:
如果输入标签:
result.extend(entry)

如何将两个循环写成单行列表理解?

  [条目中的标签用于在条目中输入条目时的条目] 


I have two lists as below

tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]

I want to extract entries from entries when they are in tags:

result = []

for tag in tags:
    for entry in entries:
        if tag in entry:
            result.extend(entry)

How can I write the two loops as a single line list comprehension?

解决方案

This should do it:

[entry for tag in tags for entry in entries if tag in entry]

这篇关于如何在列表理解python框架两个for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆