如何将嵌套循环转为列表推导式提取符合条件的列表元素
问题描述
现有两个列表:
a =["my car","your car","his car","her car","their car","her bike","your house","his job"] b = ["your","her"]
需要从列表a里提取包含b中任意元素的项,同时保持这些项在a里的原有顺序,预期输出是:
out = ["your car","her car","her bike","your house"]
已经用嵌套循环实现了需求:
out = [] for z in a: for w in b: if w in z: out.append(z)
但转成列表推导式时得到了错误结果,错误代码和输出如下:
>>> [[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']]
正确写法
完全对应原嵌套循环的版本
原循环的逻辑是遍历a的每个元素z,再遍历b的每个w,只要w在z里就把z加入结果。对应的列表推导式要保持相同的循环顺序:
out = [z for z in a for w in b if w in z]
这个写法和原循环完全等价,能得到预期输出。但要注意:如果某个z同时包含b里的多个元素(比如z = "your her car"),这个写法会把z多次添加到结果里。
更严谨的版本(避免重复添加)
如果希望每个符合条件的z只出现一次(哪怕它包含b里多个元素),可以用any()函数来判断,这样更高效也不会重复:
out = [z for z in a if any(w in z for w in b)]
这个逻辑是:对a里的每个z,只要b中存在任意一个w在z里,就把z加入结果,完美匹配需求,同时保持元素原有顺序。
内容的提问来源于stack exchange,提问作者Rasec Malkic
相关产品推荐
相关产品推荐

