【问题标题】:why zip failure while resuing a map?(python function)为什么在恢复地图时压缩失败?(python函数)
【发布时间】:2013-11-16 06:30:05
【问题描述】:

我构造了一个映射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]))))

但我发现结果很奇怪。只有第一个 zip 成功,剩下的都是 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]))
{}

【问题讨论】:

  • 测试list(zip(columns, [e for e in r])).
  • @hcwhsa it return []', Proxy` 是一个只接受一个字典类型参数的类。
  • 我认为有些函数会返回一个只能迭代一次的可迭代对象。我相信shlexopen 也遇到过这种情况。
  • columnsr的类型是什么?
  • 补充一下,可以在执行两次代码之前先r = list(r),如果结果相同,分享一下吗?

标签: python python-3.x map zip


【解决方案1】:

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]

【讨论】:

    【解决方案2】:

    查看Python3 map(..) 的文档。它不返回列表;但返回一个迭代器。因此,如果您打算重复使用,请执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 1970-01-01
      • 2020-09-02
      • 2016-01-05
      • 2014-09-29
      • 2010-11-09
      • 2017-01-31
      • 1970-01-01
      相关资源
      最近更新 更多