为什么在抢救地图时拉链失败?(python函数)

时间:2013-11-16 06:30:06

标签: python python-3.x map zip

我构建了一个地图columns = map(lambda x: x[0], cur.description),并在for循环中使用它:

for r in rows:
    proxy_list.append(Proxy(dict(zip(columns, [e for e in r]))))

但我发现结果很奇怪。只有第一个拉链成功,所有左边的return {}

测试样本:

r = ('204.93.54.15', '7808', 6, 0, '', '2013-11-12 20:27:54', 0, 3217.0, 'United States', 'HTTPS')
description = (('ip', None, None, None, None, None, None), ('port', None, None, None, None, None, None), ('level', None, None, None, None, None, None), ('active', None, None, None, None, None, None), ('time_added', None, None, None, None, None, None), ('time_checked', None, None, None, None, None, None), ('time_used', None, None, None, None, None, None), ('speed', None, None, None, None, None, None), ('area', None, None, None, None, None, None), ('protocol', None, None, None, None, None, None))
columns = map(lambda x: x[0], description)

我的测试结果如下:

>>> dict(zip(columns, [e for e in r]))
{'protocol': 'HTTPS', 'level': 6, 'time_used': 0, 'ip': '204.93.54.15', 'area': 'United States', 'port': '7808', 'active': 0, 'time_added': '', 'speed': 3217.0, 'time_checked': '2013-11-12 20:27:54'}
>>> zip(columns, [e for e in r])
<zip object at 0x0000000004079848>
>>> dict(zip(columns, [e for e in r]))
{}

2 个答案:

答案 0 :(得分:3)

map在Python3中返回一个迭代器,因此在第一次迭代后它就会耗尽:

>>> columns = map(int, '12345')
>>> list(zip(columns, range(5)))
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>> list(zip(columns, range(5)))
[]

首先将其转换为list

>>> columns = list(map(int, '12345'))
>>> list(zip(columns, range(5)))
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]
>>> list(zip(columns, range(5)))
[(1, 0), (2, 1), (3, 2), (4, 3), (5, 4)]

对于您的情况,最好使用list comprehension

columns = [x[0] for x in  description]

答案 1 :(得分:1)

查看Python3 map(..)的文档。它没有返回列表;但返回一个迭代器。因此,如果您计划重复使用,请执行:

columns = list(map(lambda x: x[0], cur.description))