有以下 2 個串列
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)
我一直在嘗試轉換為串列理解。我已經按照以下方式嘗試了這個問題的建議,但我得到了錯誤的答案。謝謝你的幫助
>>> [[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']]
>>>
uj5u.com熱心網友回復:
[ELEMENT for x in a for y in b if y in x]
ELEMENT:如果滿足尾隨條件,則為右側的每次迭代生成的任何運算式
>>> 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']
uj5u.com熱心網友回復:
鑒于您所說的解決方案確實有效:
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://www.uj5u.com/houduan/505808.html
標籤:python-3.x for循环 列表理解
上一篇:如何迭代串列中的每個索引號?
