Home  >  Q&A  >  body text

Two python syntax problems

Today I am looking at an example of the divide and conquer method. The code is as follows:

def get_max(max_list):
    return max(max_list)


def solve(init_list):
    n = len(init_list)
    if n <= 2:
        return get_max(init_list)

    temp_list = (init_list[i:i+2] for i in range(0, n, 2))

    # print 'temp_list: ' + str(temp_list)
    print temp_list

    max_list = list(map(get_max, temp_list))

    return solve(max_list)

There are two questions:

1.temp_list生成的是tuple类型吗?我打印出来的结果是<generator object <genexpr> at 0x00000000023570D8>, 为什么是这样?
2. list(map(get_max, temp_list))是把map类型转成了list, 但是这里为什么要用map呢?




if __name__ == "__main__":
    test_list = [12, 2, 23, 45, 67, 3, 2, 4, 45, 63, 24, 23]
    
    print solve(test_list)
过去多啦不再A梦过去多啦不再A梦2710 days ago631

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-05-19 10:09:50

    1、init_list传入的时候就是generator
    2、list(map(get_max, temp_list)相当于[get_max(t) for t in temp_list]

    reply
    0
  • 某草草

    某草草2017-05-19 10:09:50

    1. You can refer to this wiki page.

    2. is not map类型转成了listmap不是类型,而是一个内置函数,他的作用是对temp_list里面的每个元素apply到get_max这个函数里面,最后再把结果转变成list. You can take a look at the documentation. It is recommended that the questioner read the basics of python.

    reply
    0
  • Cancelreply