[英]Find strings from a list starting with strings in another list
我有兩個列表listOne
和listTwo
例如
listOne
可以包含“關於”,“日”,“學校”
listTwo
可以包含'a','c','da','z'
我想找出listOne
所有元素,這些元素以listOne
中的元素中的字符listTwo
。 上面示例的輸出是“ about”和“ day”
我嘗試使用以下代碼實現它:
for elem1 in listTwo:
for elem2 in listOne:
if elem2.startswith(elem1):
result.append(elem2)
但我覺得它嵌套太多了。 有沒有更優雅的方法可以在Python中實現呢?
您這樣做的方式很好。 很容易閱讀/理解等。
但是,如果您確實需要,可以使用itertools.product
將其壓縮下來:
from itertools import product
result = [elem2 for elem1, elem2 in product(listTwo, listOne) if elem2.startswith(elem1)]
您可以將一個元組傳遞給str.startswith
方法。
從文檔 :
str.startswith(prefix [,start [,end]]):如果字符串以前綴開頭,則返回True,否則返回False。 prefix也可以是要查找的前綴的元組。 使用可選的開始,測試字符串從該位置開始。 在可選端,停止在該位置比較字符串。
但這在Python 2.5+中受支持
tuple_listTwo = tuple(listTwo)
[ele for ele in listOne if ele.startswith(tuple_listTwo)]
輸出:
['day','about']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.