問題
我想從我擁有的平面串列中創建一個字典字典,以便添加一條“順序性”資訊,但我在找到解決方案時遇到了一些麻煩。
該串列類似于
a = ['Q=123', 'W=456', 'E=789', 'Q=753', 'W=159', 'E=888']
我正在拍攝dict:
dictionary = {
'Step_1': {
'Q=123',
'W=456',
'E=789'
},
'Step_2': {
'Q=753',
'W=159',
'E=888'
}
}
我想最終得到一個具有任意數量的函式Steps,以便將其應用于我的資料集。假設在資料集中有類似a1 <= n <6的串列Steps。
我的點子
到目前為止,我想出了這個:
nsteps = a.count("Q")
data = {}
for i in range(nsteps):
stepi = {}
for element in a:
new = element.split("=")
if new[0] not in stepi:
stepi[new[0]] = new[1]
else:
pass
data[f"Step_{i}"] = stepi
但它沒有按預期作業:最終字典中的兩個步驟都包含Step_1. 關于如何解決這個問題的任何想法?
uj5u.com熱心網友回復:
一種方法是:
a = ['Q=123', 'W=456', 'E=789', 'Q=753', 'W=159', 'E=888']
indices = [i for i, v in enumerate(a) if v[0:2] == 'Q=']
dictionary = {f'Step_{idx 1}': {k: v for k, v in (el.split('=') for el in a[s:e])}
for idx, (s, e) in enumerate(zip(indices, indices[1:] [len(a)]))}
print(dictionary)
{'Step_1': {'Q': '123', 'W': '456', 'E': '789'},
'Step_2': {'Q': '753', 'W': '159', 'E': '888'}}
細節:
a = ['Q=123', 'W=456', 'E=789', 'Q=753', 'W=159', 'E=888']
# Get indices where a step starts.
# This could handle also steps with variable amount of elements and keys starting with 'Q' that are not exactly 'Q'.
indices = [i for i, v in enumerate(a) if v[0:2] == 'Q=']
# Get the slices of the list starting at Q and ending before the next Q.
slices = list(zip(indices, indices[1:] [len(a)]))
print(slices)
# [(0, 3), (3, 6)]
# Get step index and (start, end) pair for each slice.
idx_slices = list(enumerate(slices))
print(idx_slices)
# [(0, (0, 3)), (1, (3, 6))]
# Split the strings in the list slices and use the result as key-value pair for a given start:end.
# Here an example for step 1:
step1 = idx_slices[0][1] # This is (0, 3).
dict_step1 = {k: v for k, v in (el.split('=') for el in a[step1[0]:step1[1]])}
print(dict_step1)
# {'Q': '123', 'W': '456', 'E': '789'}
# Do the same for each slice.
step_dicts = {f'Step_{idx 1}': {k: v for k, v in (el.split('=') for el in a[s:e])}
for idx, (s, e) in idx_slices}
print(step_dicts)
# {'Step_1': {'Q': '123', 'W': '456', 'E': '789'}, 'Step_2': {'Q': '753', 'W': '159', 'E': '888'}}
uj5u.com熱心網友回復:
你快到了。您計算“Q”數量的方式是錯誤的,并且某些代碼行的縮進錯誤(例如data[f"Step_{i}"] = stepi)
a = ['Q=123', 'W=456', 'E=789', 'Q=753', 'W=159', 'E=888']
def main():
nsteps = len([s for s in a if "Q" in s])
data = {}
for i in range(nsteps):
stepi = {}
for element in a:
new = element.split("=")
if new[0] not in stepi:
stepi[new[0]] = new[1]
data[f"Step_{i}"] = stepi
return data
if __name__ == "__main__":
data = main()
uj5u.com熱心網友回復:
第一個按這樣的專案分組:
a = ['Q=123', 'W=456', 'E=789', 'Q=753', 'W=159', 'E=888']
o = groupby(sorted(a, key=lambda x: x[0]), key=lambda x: x[0])
然后像這樣創建一個字典:
d = {i: [j[1] for j in g] for i, g in o}
然后迭代它們并得到你的結果:
result = {f"step_{i 1}": [v[i] for v in r.items()] for i in range(len(max(r.values(), key=len)))}
結果將是:
Out[47]: {'step_1': ['E=789', 'Q=123', 'W=456'], 'step_2': ['E=888', 'Q=753', 'W=159']}
uj5u.com熱心網友回復:
根據我從您的問題中了解到的情況:
我們可以對串列中的專案進行分組,在這種情況下,一組三個元素,一次回圈三個元素。
在這個答案的幫助下:
from itertools import zip_longest
a = ['Q=123', 'W=456', 'E=789', 'Q=753', 'W=159', 'E=888']
def grouper(n, iterable):
args = [iter(iterable)] * n
return zip_longest(*args)
result = dict()
for i, d in enumerate(grouper(3, a), start=1):
dict.update({f"Step_{i}": set(d)})
print(result)
{
'Step_1': {'E=789', 'Q=123', 'W=456'},
'Step_2': {'E=888', 'Q=753', 'W=159'}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477312.html
