有以下两个列表
a =["my car","your car","his car","her car","their car","her bike","your house","his job"]
b = ["your","her"]我试图从list a中获取元素,该元素包含list b中的元素字符串,顺序相同,因此预期的输出如下
out = ["your car","her car","her bike","your house"]我对嵌套for循环的尝试是这样的
out = []
for z in a:
for w in b:
if w in z:
out.append(z)我被困在试图转化为清单理解。我已经尝试了this问题的建议,但我得到了错误的答案。谢谢你的帮助
>>> [[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']]
>>>发布于 2022-09-08 06:06:16
[ELEMENT for x in a for y in b if y in x]元素:在满足尾随条件的情况下,为其右侧的每次迭代定义哪个表达式。
>>> 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']发布于 2022-09-08 06:06:08
考虑到您说的解决方案确实有效:
out = []
for z in a:
for w in b:
if w in z:
out.append(z)将其转换为列表理解基本上就像读取堆栈。
out = [z for z in a for w in b if w in z]https://stackoverflow.com/questions/73644294
复制相似问题