str_list = ['Alex is a good boy',
'Ben is a good boy',
'Charlie is a good boy']
matches = ['Charlie','good']
我想回傳 中的第三個元素str_list,因為它同時包含 'Charlie' 和 'good'。
我努力了:
[s for s in str_list if all([m in s for m in matches])][0]
但這對我來說似乎過于冗長。請更優雅的解決方案。
根據下面的回答和評論,我們有:
next(s for s in str_list if all(m in s for m in matches))
它顯然更快(但微不足道)和更整潔。
uj5u.com熱心網友回復:
我會使用該filter函式,它回傳一個迭代器,因此如果與next
next(filter(lambda s: all(m in s for m in matches), str_list))
@Timus 建議的更清晰的方法
next(s for s in str_list if all(m in s for m in matches))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381641.html
上一篇:同步兩個String物件
下一篇:將串列內容轉換為字串
