重复使用地图时为什么会导致压缩失败?(Python函数)

4
我使用 map(lambda x: x[0], cur.description) 构建了一个映射表,然后在 for 循环中使用它:
for r in rows:
    proxy_list.append(Proxy(dict(zip(columns, [e for e in r]))))

但是我发现结果很奇怪。只有第一个zip成功了,其他的都返回了{}

测试样例:

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]))
{}

测试 list(zip(columns, [e for e in r])) - Ashwini Chaudhary
@hcwhsa,它返回[]Proxy是一个只接受一个字典类型参数的类。 - Mithril
我认为有些函数会返回一个可迭代对象,但只能迭代一次。我相信我在使用 shlexopen 时遇到过这种情况。 - bozdoz
columnsr的类型是什么? - Ashwini Chaudhary
另外,你能在执行代码两次之前做 r = list(r) 吗?并分享一下是否得到了相同的结果? - UltraInstinct
@hcwhsa,@Thrustmaster 我已经更新了问题。 - Mithril
2个回答

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)]

根据您的情况,最好使用列表推导式

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

1

查看Python3 map(..)的文档。它不会返回一个列表,而是返回一个迭代器。因此,如果您计划重复使用,则应该执行以下操作:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接