Python:计算天干地支
亲测有效!!!
用Sublime编写,在CMD中运行正常
tianGan_list=["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"] #天干列表
diZhi_list=["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"] #地支列表
shengXiao_list=["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"] #属相列表
inputYear=input("请输入年份:") #输入年份
if inputYear.isdigit()==True:
inputYear=int(inputYear)
if inputYear-2020>=0: #以2020年为基准,2020年之后的年份使指针向右移动
tgPointer=abs(inputYear-2020)%10+6
if tgPointer>9:
tgPointer=abs(inputYear-2020)%10+6-10 #2020年是庚子年,“庚“在天干列表的序号为6,天干指针向后移动以6为基准,超过9后往前开始
else:
tgPointer=abs(inputYear-2020)%10+6
dzPointer=abs(inputYear-2020)%12 #“子“在地支列表的序号为0,地支指针向后移动以0为基准
else: #2020年之前的年份使列表指针往左移动
if abs(inputYear-2020)%10==0:
tgPointer=abs(inputYear-2020)%10+6 #当输入年份与2020年差值满一个天干时,指针不动,仍为6(与2020年相同)
else:
tgPointer=6-abs(inputYear-2020)%10 #当输入年份与2020年差值不满一个天干时,指针以6为基准向左移动,有可能移动超过6,进而出现负数
if abs(inputYear-2020)%12==0:
dzPointer=abs(inputYear-2020)%12 #当输入年份与2020年差值满一个地支时,指针不动,仍为0(与2020年相同)
else:
dzPointer=12-(abs(inputYear-2020)%12) #当输入年份与2020年差值不满一个地支时,指针以0为基准向左移动(不能有负数,需要用12减)
if tgPointer>=0 and tgPointer<=9:
tianGan=tianGan_list[tgPointer] #天干指针在正常范围内,直接调取天干列表内容
else:
tianGan=tianGan_list[tgPointer+10] #天干指针出现负值,用6减,确保在正常范围内,然后调取天干列表内容
diZhi=diZhi_list[dzPointer] #9/17/19行地支不可能出现负值,所以没必要再进行选择,直接调取地支列表内容即可
shengXiao=shengXiao_list[dzPointer] #生肖与地支一一对应
print("{}年是{}{}{}年".format(inputYear,tianGan,diZhi,shengXiao))
else:
print("输入错误,请重新输入!")