错误:Append()只接受一个参数(给定3个)



这就是我目前所拥有的:

seasons = ["Spring", "Summer", "Fall", "Winter"]
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
combined = []
for s in seasons:
for m in months:
combined.append(months[0:2] , "is in the season " , seasons[3])
combined.append(months[3:5] , "is in the season " , seasons[0])
combined.append(months[6:8] , "is in the season" , seasons[2])
combined.append(months[9:11] , "is in season" , seasons[0])

我得到一个错误,说append((只接受一个参数(给定3个(我有点理解这个错误的含义,但不知道如何修复它,有人能修复吗,将不胜感激

以下是获取12个条目的方法:

seasons = ["Winter", "Spring", "Summer", "Fall"]
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
combined = []
for i,s in enumerate(seasons):
for m in months[i*3:i*3+3]:
combined.append( m + " is in the season " + s )
print(combined)

输出:

['January is in the season Winter', 'February is in the season Winter', 'March is in the season Winter', 'April is in the season Spring', 'May is in the season Spring', 'June is in the season Spring', 'July is in the season Summer', 'August is in the season Summer', 'September is in the season Summer', 'October is in the season Fall', 'November is in the season Fall', 'December is in the season Fall']

months[0:2] , "is in the season " , seasons[3]不是构造字符串的正确方法。你似乎被print()的行为弄糊涂了

相反,您希望首先构造一个字符串,然后将该字符串append()添加到列表中。

def make_string(months, season):
p1 = ", ".join(months)
return p1 + " is in the season " + season

在这里,我们通过用逗号连接序列months的所有元素来创建p1。然后,我们将字符串literal和季节附加到它,并返回该值。使用此功能:

s = make_string(months[0:2], seasons[3])
combined.append(s)
s = make_string(months[3:5], seasons[0])
combined.append(s)
s = make_string(months[6:8], seasons[1])
combined.append(s)
s = make_string(months[9:11], seasons[2])
combined.append(s)

哪个给出:

combined = ['January, February is in the season Winter',
'April, May is in the season Spring',
'July, August is in the season Summer',
'October, November is in the season Fall']

请注意,您不需要循环,因为您从不使用循环变量

最新更新