用映射替换for循环

2024-05-03 20:22:13 发布

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

我正在尝试用一个map函数替换下面的for循环, 我假设它一定是像map(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)

Tags: 函数inmapforinputtimelinerange
1条回答
网友
1楼 · 发布于 2024-05-03 20:22:13

正如Willem Van Onsem在评论中所说,map在python3中是懒惰的。与Python 2中的情况不同,map将返回一个生成器,而不是像Python 2那样立即将该函数应用于所有项并返回一个生成器,而您需要迭代该生成器才能实际执行转换:

>>> 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是一些“映射对象”(即映射生成器)。为了实际生成值并调用函数,我们必须首先迭代此生成器:

^{pr2}$

如果您想取回一个列表,还可以在结果上调用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字典),所以在它的确切上下文之外它并没有真正的用处,所以您可以在这里简单地内联功能。然后甚至可以提取逻辑,这样就可以得到一个只处理输入并返回hours字典的函数。再加上^{}这看起来真的很不错:

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 }

相关问题 更多 >