【问题标题】:Using regex or string delimiter to get the expected value from the dictionary使用正则表达式或字符串分隔符从字典中获取预期值
【发布时间】:2021-07-02 14:58:22
【问题描述】:

我在下面显示的 python 列表中有一个 dict,其中键是接口,值是字符串。我需要将值转换为 int 但不能因为 eg.100-110 的字符串。我应该使用正则表达式还是有一个简单的方法来找出我从字典中得到的字符串值中的 2。可以使用正则表达式或字符串分隔符使用连字符分隔,然后在范围内找到数字 2。或者,一旦我使用了字符串分隔符,我应该将其转换为某种范围。

由连字符分隔的数字是例如 100-110 的范围。一旦我有了范围,我就可以验证否。 2 落在那个范围内,得到相应的接口。有时字符串可能采用这种模式4,6,7,8,12-15,8。需要找到这个模式中的 2 号,它也有连字符。

[{'eth1/1': '100-110', 'eth1/2': '100-110', 'eth1/3': '1-4094', 'eth1/4': '1- 4094','eth1/5':'1-4094','eth1/6':'1-4094','eth1/7':'1-4094','eth1/8':'1-4094' , 'eth1/9': '1-4094', 'eth1/10': '1-4094', 'eth1/11': '1-4094', 'eth1/12': '1-4094', ' eth1/13': '2,5-10,49,59,66', 'eth1/14': '1-4094', 'eth1/15': '1-4094', 'eth1/16': ' 1-4094','eth1/17':'1-4094','eth1/18':'1-4094','eth1/19':'1-4094','eth1/20':'2, 5-10,49,59,66', 'eth1/21': '1-4094', 'eth1/22': '1-4094', 'eth1/23': '1-4094', 'eth1/ 24':'1-4094','eth1/25':'1-4094','eth1/26':'1-4094','eth1/27':'1-4094','eth1/28' :'1-4094','eth1/29':'1-4094','eth1/30':'1-4094','eth1/31':'1-4094','eth1/32':' 1-4094','eth1/33':'1-4094','eth1/34':'1-4094','eth1/35':'2,5-10,49,59,66',' eth1/36':'1-4094','eth1/37':'1-4094','eth1/38':'1-4094','eth1/39':'1-4094','eth1/ 40':'1-4094','eth1/41':'1-4094','eth1/42':'1-4094','eth1/43':'1-4094','eth1/44' : '2,5-10,49,59,66', 'eth1/45': '1-4094', 'eth1/46': '1-4094', 'eth1/47': '1-4094', 'eth1/48': '1-4094'}]

【问题讨论】:

  • 似乎与您拥有的数据一样,您可以单独使用.split('-') 而不是正则表达式来分隔两个值(然后根据需要解析为数字)。
  • 为什么字典在列表中?列表中可以有多个字典吗?
  • @JanKyuPeblik 它并不总是 2 个值。它是逗号分隔的数字和范围的混合体。
  • @Barmar 如果我要对多个开关进行 API 调用,则可能存在多个 dicts。所以一个字典列表。在这种情况下,我正在测试一个交换机,我可以在其中发现 vlan 2 存在于我检索的值中。这可以是范围或逗号分隔的值。

标签: python regex string list dictionary


【解决方案1】:

编写一个函数,接受其中一个字符串并测试其中是否有值:

def in_nums_or_ranges(n, list_string):
    values = list_string.split(',')
    for item in values:
        if item.isnumeric():
            if n == int(item):
                return True
        else:
            start, end = map(int, item.split('-'))
            if n in range(start, end+1):
                return True
    return False

然后找到匹配的字典元素:

search_val = 2
matches = {key: value for key, value in d.items() if in_nums_or_ranges(search_val, value)}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 2019-05-02
    • 2012-02-15
    • 1970-01-01
    相关资源
    最近更新 更多