我想將這兩個 python 串列交集:
list_1_begin = ["i", "love", "to", "eat", "fresh", "apples", "yeah", "eat", "fresh"]
list_2_find = ["eat", "fresh"]
我的預期結果應該是這樣的:
expected result = ["0", "0", "0", "1", "1", "0", "0", "1", "1"]
這可以通過兩個 for 回圈來完成,但是如果我有第一個 10000 個元素的串列和第二個 100 個元素的串列,這句話也可以重復多次。有沒有 Pythonic 的方法?
重要的:
例如:
list_1_begin = ["i", "love", "to", "eat", "the", "fresh", "apples", "yeah", "eat", "fresh"]
list_2_find = ["eat", "fresh"]
解決方案應如下所示:
expected result = ["0", "0", "0", "0", "0", "0", "0", "0", "1", "1"]
所以只有當所有元素list_2_find都list_1_begin在精確的順序
uj5u.com熱心網友回復:
為了保持Python的,高效的轉換list_2_find到組,并使用串列理解:
list_1_begin = ["i", "love", "to", "eat", "fresh", "apples", "yeah", "eat", "fresh"]
list_2_find = ["eat", "fresh"]
set_2_find = set(list_2_find)
result = [str(int(e in set_2_find)) for e in list_1_begin]
print(result)
輸出
['0', '0', '0', '1', '1', '0', '0', '1', '1']
作為將 bool 格式化為 int 的替代方法,一種方法是使用f 字串,如下所示:
result = [f"{(e in set_2_find):d}" for e in list_1_begin]
輸出
['0', '0', '0', '1', '1', '0', '0', '1', '1']
可以在此處找到有關f 字串格式的一些其他資訊。
更新
如果匹配必須是連續的,請使用:
from itertools import chain
list_1_begin = ["i", "love", "to", "eat", "the", "fresh", "apples", "yeah", "eat", "fresh"]
list_2_find = ["eat", "fresh"]
len_1 = len(list_1_begin)
len_2 = len(list_2_find)
pos = chain.from_iterable([range(e, e len_2) for e in range(len_1) if list_1_begin[e:e len_2] == list_2_find])
positions_set = set(pos)
result = [f"{(i in positions_set):d}" for i in range(len_1)]
print(result)
輸出
['0', '0', '0', '0', '0', '0', '0', '0', '1', '1']
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324848.html
