if else循环一个月又几天的问题 问题解决方法日历方法

问题描述

为什么下面的代码输出错误,我将输出放在下面

(某些人可能建议使用日期时间模块,由于主程序存在一些复杂性,因此我将使用这种方法


import numpy as np
import pyvista as pv


def schwarz_D(x,y,z,linear_term=0):
        """This is the function for the Schwarz Diamond level surface."""
        return (np.sin(x) * np.sin(y) * np.sin(z) + np.sin(x) * np.cos(y) * np.cos(z) +
                np.cos(x) * np.sin(y) * np.cos(z) + np.cos(x) * np.cos(y) * np.sin(z)) - linear_term * z


# Create the grid
[nx,ny,nz] = [2,2,8]  # amount of unit cells
cell_size = 1
gradient_value = 0.04  # only values below 0.1 produce the desired geometry; this term is essential
x,z = np.mgrid[-cell_size*(nx + 1)/2:cell_size*(nx + 1)/2:100j,-cell_size*(ny + 1)/2:cell_size*(ny + 1)/2:100j,-cell_size*(nz + 1)/2:cell_size*(nz + 1)/2:100*2j] * np.pi / (cell_size/2)


# make a grid and exclude cells below 0.1
grid = pv.StructuredGrid(x,z)
grid['scalars'] = schwarz_D(x,gradient_value).ravel(order='F')
contour = grid.clip_scalar(value=0.1)


# make a bunch of clips
# bounds = contour.bounds
# contour.clip(origin=(bounds[0] + cell_size/2,0),normal='-x',inplace=True)
# contour.clip(origin=(0,bounds[1] - cell_size/2,normal='-y',bounds[2] + cell_size/2),normal='-z',inplace=True)
# contour.clip(origin=(bounds[3] - cell_size/2,normal='x',bounds[4] + cell_size/2,normal='y',bounds[5] - cell_size/2),normal='z',inplace=True)

contour.plot(smooth_shading=True,color='w')

我得到这个输出

    months = [1,3,4,5,6,7,8,9,10,11,12]
    for month in months:
        if month == {1,11}:
            days= 31
            print(days)
        elif month == {4,12}:
            days = 30
            print(days)
        else :
            days = 28
            print(days)

解决方法

问题解决方法

您正在检查整数是否等于集合。您要检查整数是否在集合中。顺便说一句,您使用的集是错误的(此处已修复),二月可能有29天(此解决方案中未修复)。

for month in range(1,13):
    if month in {1,3,5,7,8,10,12}:
        days = 31
    elif month in {4,6,9,11}:
        days = 30
    else :
        days = 28
    print(f"{month:2}: {days}")
 1: 31
 2: 28
 3: 31
 4: 30
 5: 31
 6: 30
 7: 31
 8: 31
 9: 30
10: 31
11: 30
12: 31

日历方法

另一种解决方案是使用calendar模块来修复2月29日的问题。

import calendar


for month in range(1,13):
    days = calendar.monthrange(2020,month)[1]
    print(f"{month:2}: {days}")
 1: 31
 2: 29
 3: 31
 4: 30
 5: 31
 6: 30
 7: 31
 8: 31
 9: 30
10: 31
11: 30
12: 31