我有一長串字串(或 Pandas 資料框中的列),我希望能夠根據不同參考串列中的某些值從中分離字串。我想用pythonic的方式完成它,而不僅僅是迭代和匹配。
Input:
my_list_or_column = ["this is a test", "blank text", "another test", "do not select this" ]
ref_list = ["test", "conduct"]
現在,我應該能夠分離在 ref_list 中有一個單詞的句子。
Output:
match = ["this is a test" .... ]
did_not_match = ["do not select this"]
有什么幫助嗎?
uj5u.com熱心網友回復:
怎么樣:
my_list_or_column = ["this is a test", "blank text", "another test", "do not select this" ]
ref_list = ["test", "conduct"]
def is_contain(col):
for ref in ref_list:
if ref in col:
return True
return False
print(list(filter(lambda x: is_contain(x), my_list_or_column)))
uj5u.com熱心網友回復:
您可以轉換ref_list為一個集合并查看它,而不是迭代一個串列。這可能很有用,特別是如果ref_list很大。
did_not_match = []
match = []
my_set = set(ref_list)
for string in my_list_or_column:
set_string = set(string.split())
if set_string - my_set != set_string:
match.append(string)
else:
did_not_match.append(string)
由于您提到這my_list_or_column可能是一個 Pandas DataFrame 列,您還可以為相關文本創建一個布爾掩碼和過濾器:
my_Series = pd.Series(my_list_or_column)
mask = my_Series.str.contains('|'.join(ref_list))
match = my_Series[mask].tolist()
did_not_match = my_Series[~mask].tolist()
輸出:
>>> print(match)
['this is a test', 'another test']
>>> print(did_not_match)
['blank text', 'do not select this']
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388306.html
上一篇:串列和字典的串列列
下一篇:如何列出串列的元素
