我有一個字串和一個串列:
my_string = "one two three"
my_list = ["one", "two", "three", "four"]
我想找到其中的所有子my_string字串my_list。
這是我嘗試過的:
matches = []
if any((match := sub_string) in my_string for sub_string in my_list):
matches.append(match)
如果我列印匹配,結果是:
["one"]
我打算讓結果是:
["one", "two", "three"]
顯然,一旦找到一個匹配項,我的代碼就會放棄搜索其他匹配項。問題:
- 我怎樣才能編輯它來做我需要的?
- 有沒有更快的方法來做我需要的事情?
uj5u.com熱心網友回復:
你可以用串列理解來做到這一點,
In [1]: [item for item in my_list if item in my_string]
Out[1]: ['one', 'two', 'three']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/518390.html
標籤:Python细绳列表
