簡體   English   中英

從另一個列表中的字符串開始的列表中查找字符串

[英]Find strings from a list starting with strings in another list

我有兩個列表listOnelistTwo

例如

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM