1

我有:

*MONTHS =(“一月”、“二月”、“三月”、...“十二月”)(包括所有月份)

我应该输入一个月的 3 个字母缩写并获取该月的索引值。到目前为止,我有:

for M in MONTHS:
    shortMonths = M[0:3]
    print shortMonths

1 月 2 月 3 月 4 月 5 月 6 月 7 月 8 月 9 月 10 月 11 月 12 月

我注意到 shortMonths 中的输出月份没有引号,这使得无法测试缩写是否在 shortMonths 中:

MMM =“二月”

print list(shortMonths).index(MMM) + 1 # 考虑到列表的第一个月,一月,是月份 0+1 = 1,以此类推所有月份

ValueError:“Feb”不在列表中

如何在不创建函数的情况下解决此问题?另外,这是一道作业题。而且,我们不允许使用字典、地图或日期时间

4

5 回答 5

1

听起来您想shortMonths成为一个列表,但您只是为其分配了一个字符串。

我想你想要这样的东西:

shortMonths = [] # create an empty list
for M in MONTHS:
    shortMonths.append(M[0:3]) # add new entry to the list
print shortMonths # print out the list we just created

或使用列表理解

# create a list containing the first 3 letters of each month name
shortMonths = [M[0:3] for M in MONTHS]
print shortMonths # print out the list we just created
于 2013-10-17T06:02:01.867 回答
0
abbr = raw_input("Enter the month abbr:")


months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
months_abbr = [month.lower()[:3] for month in months]
index = months_abbr.index(abbr.lower())
if index >= 0:
    print "abbr {0} found at index {1}".format(abbr, index)
else:
    print "abbr {0} not found".format(abbr)
于 2013-10-17T09:41:13.150 回答
0

shortMonths 是字符串而不是列表。如下做。

shortMonths = []
  for M in MONTHS:
    shortmonths.append(M[0:3])
于 2013-10-17T06:11:44.320 回答
0
>>> months = ["January", "Febuary", "March", "April"]
>>> search = "Mar"
>>> [i for i, mo in enumerate(months) if search == mo[0:3]][0]
2
>>> search = "Fan"
>>> [i for i, mo in enumerate(months) if search == mo[0:3]][0]
IndexError: list index out of range
于 2013-10-17T08:00:55.433 回答
0

这很简单:

>>> months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
>>> search = "Jan"
>>> months.index([i for i in months if i[:3].lower() == search.lower()][0])+1
1
>>> # Or
... def getmonth(search):
...    for i in months:
...        if i[:3].lower() == search.lower():
...            return x.index(i)+1
>>> getmonth("Feb")
2

要捕获错误:

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
while True:
    search = ""
    while len(search) != 3:
        search = raw_input("Enter first 3 letters of a month: ")[:3]
    month = [i for i in months if i[:3].lower() == search.lower()]
    if not month: # Not in the list, empty list: []
        print "%s is not a valid abbreviation!"%search
        continue
    print months.index(month[0])+1
于 2013-10-17T09:10:35.013 回答