我在Python中使用了calendar.py模块:
for day in list(calendar.monthcalendar(2017,calmonth)):
print(day)
创建一个月的矩阵:
[0, 0, 0, 0, 0, 0, 1]
[2, 3, 4, 5, 6, 7, 8]
[9, 10, 11, 12, 13, 14, 15]
[16, 17, 18, 19, 20, 21, 22]
[23, 24, 25, 26, 27, 28, 29]
[30, 31, 0, 0, 0, 0, 0]
我想将其转换为一个简单的列表,如:
(1,2,3,4....31)
这意味着摆脱零并将矩阵转换为列表。
我试过把它变成一个有numpy的数组:
for day in list(calendar.monthcalendar(2017,calmonth)):
print(day)
dayarray = np.squeeze(np.asarray(day))
print(dayarray)
但是没有其他用于摆脱零或转换为列表的numpy公式似乎有效。
答案 0 :(得分:2)
无需使用monthcalendar
,calendar.py
功能更适合您的需求:
_, ndays = calendar.monthrange(2017, 12)
l = list(range(1, ndays+1))
print(l)
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
答案 1 :(得分:0)
你可以用两个for循环来提取它:
my_matrix = [[0, 0, 0, 0, 0, 0, 1],
[2, 3, 4, 5, 6, 7, 8],
[9, 10, 11, 12, 13, 14, 15],
[16, 17, 18, 19, 20, 21, 22],
[23, 24, 25, 26, 27, 28, 29],
[30, 31, 0, 0, 0, 0, 0]]
my_list = []
for array in my_matrix:
for i in array:
if i>0:
my_list.append(i)
print(my_list)