我有兩個串列,其中串列 A 的元素包含在串列 B 的元素中。請注意,此示例中的順序非常重要。
A = ['pent', 'tri', 'rec', 'oct', 'hex']
B = ['triangle', 'rectangle', 'pentangle', 'hexagon', 'octagon']
我想遍歷 A 和 B 以及在 B 中找到 A 的任何地方,將其添加到字典中,然后將其添加到字典中。
d = {'prefix': a, 'shape':b}
l = [{'prefix': 'pent', 'shape':'pentangle'}, {'prefix':'tri' , 'shape':'triangle'}, {'prefix': 'rec', 'shape':'rectangle'},...]
我嘗試使用 zip 函式,但我認為因為 B 相對于 A 是無序的,所以它不起作用
dict_list = []
for i,j in zip(A,B):
if i in j:
d = {'prefix': i, 'shape':j}
dict_list.append(d)
我知道我可以做一些類似“for i in A if i in B”的事情,但是我不知道將匹配值放入我的字典的語法。
我認為這是一個非常基本的問題,我只是無法讓它發揮作用。這應該與 zip 一起使用嗎?我想也可以預先填充前綴,然后以某種方式使用它來查找形狀,但同樣,我不確定語法。在某些情況下,我使用的串列是 1000 多條記錄,因此我無法手動執行此操作。
uj5u.com熱心網友回復:
您可以使用串列理解。這可能不是最有效的方法,但至少語法很容易理解。
A = ['pent', 'tri', 'rec', 'oct', 'hex']
B = ['triangle', 'rectangle', 'pentangle', 'hexagon', 'octagon']
dict_list = [{'prefix': a, 'shape': b} for a in A for b in B if b.startswith(a)]
print(dict_list) # [{'prefix': 'pent', 'shape': 'pentangle'}, {'prefix': 'tri', 'shape': 'triangle'}, {'prefix': 'rec', 'shape': 'rectangle'}, {'prefix': 'oct', 'shape': 'octagon'}, {'prefix': 'hex', 'shape': 'hexagon'}]
uj5u.com熱心網友回復:
您可以嘗試使用生成器進行串列理解:
[{'prefix': x, 'shape': next((y for y in B if y.startswith(x)))} for x in A]
輸出:
[{'prefix': 'pent', 'shape': 'pentangle'},
{'prefix': 'tri', 'shape': 'triangle'},
{'prefix': 'rec', 'shape': 'rectangle'},
{'prefix': 'oct', 'shape': 'octagon'},
{'prefix': 'hex', 'shape': 'hexagon'}]
或者您可以先排序B為與以下相同的順序A:
B = sorted(B, key=lambda x: next((i for i, v in enumerate(A) if x.startswith(v))))
然后只是zip:
[{'prefix': x, 'shape': y} for x, y in zip(A, B)]
uj5u.com熱心網友回復:
不像 j1-lee 的版本那么簡潔,但復雜度更高(O(#A log #A #B log #B) 而不是 O(#A * #B)):
from collections import deque # heap would be more efficient, but verbose
prefixes = sorted(A) # sorting is the most expensive part
shapes = deque(sorted(B))
l = [] # now it's just linear scan
for prefix in prefixes:
while shapes and prefix<shapes[0] and shapes[0].startswith(prefix):
l.append({'prefix': prefix, 'shape': shapes.popleft()})
注意:它不保留A的順序。可以通過排序和操作索引來實作,但會使代碼有點晦澀。執行后,l將是:
[{'prefix': 'hex', 'shape': 'hexagon'},
{'prefix': 'oct', 'shape': 'octagon'},
{'prefix': 'pent', 'shape': 'pentangle'},
{'prefix': 'rec', 'shape': 'rectangle'},
{'prefix': 'tri', 'shape': 'triangle'}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/310937.html
上一篇:在二進制字串中查找子字串
