提问者:小点点

正在根据列表从搜索字符串中检索“x”


我试图从字典(dict)中打印'x'的值,在它从字符串(str)中找到与列表(list)中的任何元素匹配之后。

>>> dict = {'c3750': 'switch', 'vsrx': 'vfirewall'}
>>> list = ['c3750', 'vsrx']               
>>> str = "Juniper Networks, Inc. firefly-perimeter internet router, kernel JUNOS 12.1X47-D15.4 #0: 2014-11-12 02:13:59 UTC     builder@chamuth.juniper.net:/volume/build/junos/12.1/service/12.1X47-D15.4/obj-i386/junos/bsd/kernels/VSRX/kernel Build date: 2014-11-12 "
>>> if any(x in str.lower() for x in list):        
...   print "{}".format(dict['x'])                 
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'x'

预期结果:它应返回“vfirewall”。


共2个答案

匿名用户

Try应该是您正在寻找的内容:

dct = {'c3750': 'switch', 'vsrx': 'vfirewall'}
lst = ['c3750', 'vsrx']
s = "Juniper Networks, Inc. firefly-perimeter internet router, kernel JUNOS 12.1X47-D15.4 #0: 2014-11-12 02:13:59 UTC     builder@chamuth.juniper.net:/volume/build/junos/12.1/service/12.1X47-D15.4/obj-i386/junos/bsd/kernels/VSRX/kernel Build date: 2014-11-12 "

for x in lst:
    if x in s.lower():
        print("{}".format(dct[x]))

您应该使用循环来搜索列表中的每个元素。

匿名用户

你是说这样的事吗?

dd = {'c3750': 'switch', 'vsrx': 'vfirewall'}
ll = ['c3750', 'vsrx']               
ss = "Juniper Networks, Inc. firefly-perimeter internet router, kernel JUNOS 12.1X47-D15.4 #0: 2014-11-12 02:13:59 UTC     builder@chamuth.juniper.net:/volume/build/junos/12.1/service/12.1X47-D15.4/obj-i386/junos/bsd/kernels/VSRX/kernel Build date: 2014-11-12 "

[dd[x] for x in ll if x in ss.lower()]

Out[1]:
    ['vfirewall']