为什么这个lambda表达式结果对象的dict转换有什么问题?

时间:2016-02-05 20:50:07

标签: python dictionary lambda casting python-netifaces

感到自鸣得意地认为我在宇宙中拥有最好的lambda表达式,以返回使用python和netifaces所需的所有相关网络信息

>>> list(map(lambda interface: (interface, dict(filter(lambda ifaddress: ifaddress in (netifaces.AF_INET, netifaces.AF_LINK), netifaces.ifaddresses(interface) )))  , netifaces.interfaces()))

但我得到了这个

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: cannot convert dictionary update sequence element #0 to a sequence

稍微缩小一点

>>>dict(filter(lambda ifaddress: ifaddress in (netifaces.AF_INET, netifaces.AF_LINK), netifaces.ifaddresses("eth0")))

问题出在哪里:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a  sequence

但我可以将过滤器对象转换为列表

 >>> list(filter(lambda ifaddress: ifaddress in (netifaces.AF_INET, netifaces.AF_LINK), netifaces.ifaddresses("eth0")))
 [17, 2]

但是,这不是我想要的。我想要它实际上是什么:

>>> netifaces.ifaddresses("tun2")
{2: [{'addr': '64.73.0.0', 'netmask': '255.255.255.255', 'peer': '192.168.15.4'}]}
>>> type (netifaces.ifaddresses("eth0"))
<class 'dict'>
那么是什么让我的演员回到字典?

1 个答案:

答案 0 :(得分:2)

当给定字典作为输入时,filter将仅迭代并从该字典返回

>>> filter(lambda x: x > 1, {1:2, 3:4, 5:6})
[3, 5]

因此,您只是将过滤后的密钥序列输入到新的字典中,而不是键值对。您可以像这样修复它:注意对items()的调用以及内部lambda如何将元组作为输入。

list(map(lambda interface: (interface, dict(filter(lambda tuple: tuple[0] in (netifaces.AF_INET, netifaces.AF_LINK), 
                                                   netifaces.ifaddresses(interface).items()))), 
         netifaces.interfaces()))

现在这不是很漂亮......我建议将代码更改为嵌套列表和字典理解:

[(interface, {ifaddress: value 
          for (ifaddress, value) in netifaces.ifaddresses(interface).items()
          if ifaddress in (netifaces.AF_INET, netifaces.AF_LINK)})
 for interface in netifaces.interfaces()]