Python问题与return语句

时间:2018-10-25 14:22:38

标签: python python-3.x

该代码以一个列表作为输入,例如:

[1995, 1750, 2018] 

,我希望它能有所回报 基本上,这段代码会搜索年份列表中每年最接近的leap年

1996
1948
2016 

全部放在单独的行中。

我用return语句返回的输出是:

1996 1748 2016

但是事情是我必须使用return,因为我使用map东西将其写入文件,但是我得到了

map argument #1 must support iteration

我的问题有解决方案吗?

#!/bin/python3

import math
import os
import random
import re
import sys

def is_leap(year):
    leap = False

    if year % 4 == 0:
        if year % 100 != 0 or year % 400 == 0:
            leap = True

    return leap

forward_list = {}
back_list = {}
newLst = []

def year_forward(yearBounds):
    for item in yearBounds:
        counter = 0
        # forwad list
        while not is_leap(item):
            item = item + 1
            counter += 1
        #forward_list.append(item)
        forward_list[item] = counter
    return forward_list


def year_backward(yearBounds):
    # back_list
    for item in yearBounds:
        counter = 0
        while not is_leap(item):
            item = item - 1
            counter -= 1
        #back_list.append(item)
        back_list[item] = counter
    return back_list

def findLastLeapYears(yearBounds):

    forward =  (year_forward(yearBounds))
    backward = (year_backward(yearBounds))
    tuple_forward = list(forward.items())
    tuple_backward = list(backward.items())

    counter = 0
    for item in tuple_forward:
        if abs(item[1]) < abs(tuple_backward[counter][1]):
            newLst.append (item[0])
            counter+=1
        elif abs(item[1]) == abs(tuple_backward[counter][1]):
            if item[0] < tuple_backward[counter][0]:
                newLst.append (item[0])
                counter += 1
            else:
                newLst.append (tuple_backward[counter][0])
                counter += 1

        else:
            newLst.append (tuple_backward[counter][0])
            counter+=1

    return newLst

通话:

leapYears = findLastLeapYears(years)

fptr.write(' '.join(map(str, leapYears)))
fptr.write('\n')

fptr.close()

2 个答案:

答案 0 :(得分:1)

您的代码运行良好,如果您希望将其放在单独的行上,请使用'\n'.join(...)

答案 1 :(得分:0)

对我来说,使用您的代码,我无法重现该错误,并且一切正常。

错误map argument #1 must support iteration表明您使用str作为覆盖默认str的变量或函数。