2017-04-09 57 views
0

我试图用地图函数替换下面的for循环, 我认为它必须是像地图(inBetween,input.split("\n")),但是当我这样做时,我的小时字典保持不变。我觉得它甚至没有进入这个功能。通过地图替换循环

有人知道如何使它工作吗?

#!/usr/local/bin/python3.5 

input='''5 
1 8 
2 3 
4 23 
4 6 
2 23''' 

hours = {} 
for time in range(1,25): 
    hours[time] = 0 
def inBetween(line): 
    print(line) 
    current = int(line.split(" ")[0]) 
    while current < int(line.split(" ")[1]): 
     hours[current] +=1 
     current += 1 
for entree in range(1, int(input.split("\n")[0])+1): 
     inBetween(input.split("\n")[entree]) 

print(hours) 
+1

这是因为,'map'在python-3.x的工作*懒*,用'名单兑现它(地图(..))' –

回答

2

正如威廉·Onsem在评论已经说了,map是懒在Python 3而不是立即应用功能,所有项目,并返回一个列表,在Python 2中的情况下,map将返回发电机,而不是你需要以遍历实际执行转换:

>>> lst = [1, 2, 3] 
>>> def square(x): 
     print('Calculating square of', x) 
     return x * x 

>>> res = map(square, lst) 
>>> res 
<map object at 0x0000029C2E4B2CC0> 

正如你所看到的,功能不运行,res是一些“地图对象”,而不是(这是地图生成器) 。我们必须以实际产生的值并调用函数首先遍历该发生器:

>>> for x in res: 
     print(x) 

Calculating square of 1 
1 
Calculating square of 2 
4 
Calculating square of 3 
9 

如果你想要得到一个列表,用户也可以直接拨打list()的结果立即拨打了功能每一个元素:

>>> list(map(square, lst)) 
Calculating square of 1 
Calculating square of 2 
Calculating square of 3 
[1, 4, 9] 

不过请注意,你的情况是不是真的适合map。据我所知,从您的代码和您的输入中可以看出,您输入的第一行是一个包含需要处理的行数的单个数字。

所以你的情况,除非你想积极地忽略第一行(和公正的处理行),你不应该使用map这里。

但是,通过存储来自split调用的结果,您可以使代码更加简单(并且更高效)。例如:

lines = input.split('\n') 
for i in range(1, int(lines[0]) + 1): 
    inBetween(lines[i]) 

在这里,你只是分裂一次不是一次对每个迭代的输入。

至于你inBetween功能,你也可以使用一个for循环在这里,这使得它简单一点:

def inBetween(line): 
    # using a tuple unpacking to get both values from the line at once 
    start, stop = line.split(' ') 
    for h in range(int(start), int(stop)): 
     hours[h] += 1 

最后,实际上并没有从这里你inBetween功能任何好处。由于它是变异的全局状态(hours字典),所以它在其确切的上下文之外并不是很有用,所以您可以简单地在此处将功能内联。你甚至可以提取逻辑,所以你得到一个函数,只处理输入并返回你的字典。与defaultdict结合这实际上可以看相当不错:

from collections import defaultdict 
def getHours(lines): 
    hours = defaultdict(int) 
    for i in range(1, int(lines[0]) + 1): 
     start, stop = lines[i].split(' ') 
     for h in range(int(start), int(stop)): 
      hours[h] += 1 
    return dict(hours) 

而这一切已经:

>>> getHours(input.split('\n')) 
{ 1: 1, 2: 3, 3: 2, 4: 4, 5: 4, 6: 3, 7: 3, 8: 2, 9: 2, 10: 2, 
11: 2, 12: 2, 13: 2, 14: 2, 15: 2, 16: 2, 17: 2, 18: 2, 19: 2, 20: 2, 
21: 2, 22: 2 }