如何创建一个包含多个相同变量的列表而不键入每个变量?(Python)

2024-09-29 20:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个代表黄道带日历的列表。它是一个小程序的一部分,接受用户输入的出生月份和出生日期。有办法吗?我还穿着逻辑尿布,可能还没到Python的子宫里。我也已经被告知,我不是很Python…我知道。你知道吗

month = ["January","February","March","April","May","June",
     "July","August","September","October","November","December"]


#The following is the list I am attempting to create
#I need it to represent 365 days but I don't want to type
#each zodiac sign thirty times. It would look ridiculous
#and would probably be considered illogical.

zodiac = [['Capricorn']*19,['Aquarius']*30,['Pisces']*30]

#You probably know with out running the above list that it only
#has three elements zodiac[0],[1],[2]... I need it to have 79.
#Is this possible?

dayOfYear= [0,31,59,90,120,151,181,212,243,273,304,334]
zodiacDay = int

birthmonth = int(raw_input('Enter your birth month(1-12): ')) - 1
while birthmonth <= 12:
    birthday = int(raw_input('Enter your birth day(1-31): '))
    while birthday < 32:
        zodiacDay = dayOfYear[birthmonth] + birthday
        print"""
You were born on the %r day of the year,
which is the %r of %s. Your Zodiac sign is %s.
""" % (dayOfYear[birthmonth] + birthday,birthday,month[birthmonth],
   zodiac[zodiacDay])
    birthmonth = int(raw_input('Enter your birth month(1-12): ')) - 1

Tags: thetoinputyourrawisitint
1条回答
网友
1楼 · 发布于 2024-09-29 20:26:49

对于如何组合包含固定值的多个列表的主要问题:

zodiac = ['Capricorn']*19 + ['Aquarius']*30 + ['Pisces']*30

这将连接字符串列表,而不是创建字符串列表。还有其他方法,但在我看来,这是最简单的,完全适合这种情况。你知道吗

对于其他建议-如果您喜欢使用一年中的某一天作为预先计算的值列表的索引,您可能会发现内置datetime.date类的^{}方法很有用。你知道吗

正如Marcin所建议的,使用范围通常是我解决这类问题的方法—按最早的天数存储符号值的索引,然后遍历该列表,直到找到一个小于或等于给定天数的索引。但是使用365元素列表来存储值并不可怕。你知道吗

如果你这么做不仅仅是为了学习,一定要考虑闰年。我对占星术了解不够,不知道该推荐什么。你知道吗

相关问题 更多 >

    热门问题