簡體   English   中英

Python:使用列表推導的非均勻數組

[英]Python: Non-Uniform Array using List Comprehension

我想使用帶有可變大小子數組的列表理解來初始化2D數組。 數組中的所有值都應該是隨機的。

請參見下面的示例-注意, dim每個數字均指子陣列的長度。

dim = [1,3,1] -> this would make the array:
[[.143],
[.534], [.732], [.741],
[.989]]

到目前為止,我已經嘗試了以下方法:

arr = [[random.random() for b in range(b)] for a in range(len(dim))]]

但是我收到錯誤NameError: name 'b' is not defined 我錯過了一些簡單的事情嗎? 我顯然可以使用使用列表附加和常規的for循環,但是我感覺還有更多的python-y方法可以做到這一點!

這是一個非常簡單的問題-正確的語法是:

arr = [[random.random() for b in range(dim[a])] for a in range(len(dim))]

暫無
暫無

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

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