首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用列表理解从两个列表之间的子字符串中获取新列表

用列表理解从两个列表之间的子字符串中获取新列表
EN

Stack Overflow用户
提问于 2022-09-08 05:57:48
回答 2查看 27关注 0票数 0

有以下两个列表

代码语言:javascript
复制
a =["my car","your car","his car","her car","their car","her bike","your house","his job"]
b = ["your","her"]

我试图从list a中获取元素,该元素包含list b中的元素字符串,顺序相同,因此预期的输出如下

代码语言:javascript
复制
out = ["your car","her car","her bike","your house"]

我对嵌套for循环的尝试是这样的

代码语言:javascript
复制
out = []
for z in a:
    for w in b:
        if w in z:
            out.append(z)

我被困在试图转化为清单理解。我已经尝试了this问题的建议,但我得到了错误的答案。谢谢你的帮助

代码语言:javascript
复制
>>> [[z for z in a] for w in z if w in z]
[['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job'], 
 ['my car', 'your car', 'his car', 'her car', 'their car', 'her bike', 'your house', 'his job']]
>>>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-08 06:06:16

代码语言:javascript
复制
[ELEMENT for x in a for y in b if y in x]

元素:在满足尾随条件的情况下,为其右侧的每次迭代定义哪个表达式。

代码语言:javascript
复制
>>> a =["my car","your car","his car","her car","their car","her bike","your house","his job"]
>>> b = ["your","her"]
>>> [x for x in a for y in b if y in x]
['your car', 'her car', 'her bike', 'your house']
票数 0
EN

Stack Overflow用户

发布于 2022-09-08 06:06:08

考虑到您说的解决方案确实有效:

代码语言:javascript
复制
out = []
for z in a:
    for w in b:
        if w in z:
            out.append(z)

将其转换为列表理解基本上就像读取堆栈。

代码语言:javascript
复制
out = [z for z in a for w in b if w in z]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73644294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档