我试图为一年中的每个月生成0到1之间的随机数:例如,一月有31天,我想生成31*24个这样的随机数并将它们存储在一个数组中。这12个月中的每个月都是一样的。我希望它们都存储在同一个表或矩阵下,可以调用这些表或矩阵进行进一步的操作。在MATLAB中,这很容易通过将for循环结果存储在cell-array中来实现。我想在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个元素(为期一年),但我希望该数组在几个月内拆分。(列大小不相等)
发布于 2019-08-13 06:29:44
可以使用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如果你想要月份名称而不是数字,你可以使用字典。
https://stackoverflow.com/questions/57468305
复制相似问题