将嵌套 for 循环迭代的结果存储在单个变量中:具有多个不同长度的列的 table

Store the result of nested for loop iteration in a single variable: A table with multiple columns of different lengths

我正在尝试为一年中的每个月生成 0 到 1 之间的随机数:例如一月有31天,我想生成31*24个这样的随机数存入数组。 12 个月中的每个月都相同。我希望它们都存储在同一个 table 或矩阵下,可以调用它们进行进一步的操作。 在 MATLAB 中,这可以通过将 for 循环结果存储在元胞数组中轻松实现。我想在 Python 中做同样的事情。如果我附加所有随机数,它们只会创建一个 loooooong 数组 (1D),但我更喜欢每个月有 12 列 1 的数组,其中随机数垂直存储。由于每个月的天数不同,每个月列的长度也会不同。

# Find the no of hours in each month in a certain year
import calendar
k = 1
hrs = np.array([])
for k in range(12):
    no_hrs = (calendar.monthrange(2020, k+1) [1])*24 # 2020 is a random year
    hrs = np.append(hrs,no_hrs)
hrs = hrs.astype(int) # no of hrs for each month
# Now we generate the random numbers and store them in an 1D array
rndm = np.array([])
k = 1
for k in range(12):
    for _ in range(hrs[(k)]):
        value = random()
        rndm = np.append(value,rndm)
    rndm # this is the array containing 366*24 elements (for a year)
# But I would like the array to be splitted in months

该数组将包含 366*24 = 8784 个元素(一年) 但我希望数组能在几个月内拆分。 (不等列大小)

可以使用 np.arrays 的列表来完成 我添加了每个数组长度的打印。

import calendar
import numpy as np
import random

k = 1
hrs = np.array([])
for k in range(12):
    no_hrs = (calendar.monthrange(2020, k+1) [1])*24 # 2020 is a random year
    hrs = np.append(hrs,no_hrs)
hrs = hrs.astype(int) # no of hrs for each month

rndm = []
k = 1
for k in range(12):
    x =  np.array([])
    for _ in range(hrs[(k)]):
        value = random.random()
        x = np.append(value,x)
    rndm.append(x)

print(len(rndm))
for k in range(12):
    print(k, len(rndm[k]))

并打印

12
0 744
1 696
2 744
3 720
4 744
5 720
6 744
7 744
8 720
9 744
10 720
11 744

如果你想要月份名称而不是数字,你可以使用字典。