简体   繁体   English

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

[英]Why what's wrong with this dict conversion of a lambda expression result object?

Was feeling smug thinking that I had the best lambda expression in the universe cooked up to return all the relevant network information ever needed using python and 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()))

but I got this 但我明白了

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

scaling it back a bit 缩小一点

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

is where the problem is: 问题出在哪里:

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

but so I can convert the filter object to a list 但是我可以将过滤器对象转换为列表

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

but, that's not what I want. 但是,那不是我想要的。 I want what it actually is: 我想要它实际上是什么:

>>> 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'>

so what's mucking up my cast back back to dictionary? 那么,是什么让我的演员阵容重新回到字典上呢?

When given a dictionary as input, filter will only iterate and return the keys from that dictionary. 当给定字典作为输入时, filter将仅迭代并返回该字典中的

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

Thus you are feeding just the sequence of filtered keys into the new dict, not the key-value-pairs. 因此,您只将过滤后的键序列输入到新字典中,而不是键值对。 You could fix it like this: Note the call to items() and how the inner lambda is getting a tuple as input. 您可以这样修复它:注意对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()))

Now that's not very pretty... I suggest changing your code to a nested list- and dictionary-comprehension: 现在这还不是很漂亮...我建议将您的代码更改为嵌套的列表和字典理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM