简体   繁体   English

如何从 python 中的以下元组中获取 IP 地址

[英]How do i fetch the IP address from the following tuple in python

('table',
 [(1,
   {u'Node': u'1',
    u'Mode': u'a',
    u'HostName': u'hn19',
    u'Address': u'10.10.10.10'}),
   (2,
    {u'Node': u'2',
     u'Mode': u'b',
     u'HostName': u'hn20',
     u'Address': u'10.10.10.11'})]) 

Please suggest some ways to avoid loops.请提出一些避免循环的方法。 thanks in advance:)提前致谢:)

_, table = that_data_you_posted
ip_addresses = [d[u'Address'] for _, d in table]

This just hides the loop in a list comprehension.这只是在列表理解中隐藏了循环。 There's obviously no way to avoid iterating over multiple rows in a table.显然没有办法避免遍历表中的多行。

Since this is a small tuple, we can continue with using index, but when you have a larger tuple, you'll surely have to use loops.由于这是一个小元组,我们可以继续使用索引,但是当你有一个更大的元组时,你肯定必须使用循环。

For now you may try this现在你可以试试这个

#a is your tuple.
ipaddress1 = a[1][0][1][u'Address']
ipaddress2 = a[1][1][1][u'Address'] 

I hope this helped.我希望这会有所帮助。

i would have created dict of key as host, values ip.我会创建密钥字典作为主机,值 ip。

_, lst = tpl
ip_dict= { d[u'hn20'] : d[u'Address'] for _,d if u'hn20' in d and u'Address' in d }

the if condition is important because there are possibilities this key missing in dict. if 条件很重要,因为 dict 中可能缺少此键。

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

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