簡體   English   中英

如何將python字典轉換為2D數組並在長度不匹配的地方填充?

[英]How to convert a python dictionary to an 2D array and pad wherever there is mismatch in length?

我正在嘗試將字典項放入數組中。 鍵都是整數,但是每個值都是不同長度的列表。 我想轉換為數組並填充零。 我有以下

a = {1:[0, 1], 2:[21], 3:[]}
lmax = 0
for item in a.values():
    lmax = len(item) if len(item) > lmax else lmax
t = np.zeros(len(a), lmax)
for key in a:
    t[ key, :len(a[key]) ] = a[key]

有沒有更Python的方式來做到這一點?

謝謝

您似乎在代碼中混用了鍵和值,所以我不確定該如何工作。

一種方法是

a = {1:[0, 1], 2:[21], 3:[]}
max_length = max(len(item) for item in a.values())
t = [[0] * (max_length - len(item)) + item for item in a.values()]

或者,如果您想確保列表按“正確”的順序排列(即,原始字典中具有最低鍵的項首先顯示),則可以將其更改為

t = [[0] * (max_length - len(item)) + item for _, item in sorted(a.items())]

對於lmax,

lmax = max(map(len, a.values()))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM