【问题标题】:skipping digit/word combinations in dictionary using list使用列表跳过字典中的数字/单词组合
【发布时间】:2019-10-01 02:28:04
【问题描述】:

我有一个列表e

e = ['s', 'mm', 'ng']

还有一个字典d

d = {'A1': ['Tomas', 
            'john',
 '2s',
 'Douglas',
    '20ng'],      
 'B1': ['Tomm',        
 '3mm',
 'Sterling',
       'hey']}

我的目标是只跳过d 中以数字和e 中的元素结尾的名称。

例如,d 中的 2s 将被跳过,因为它有一个数字 2 和一个来自列表 e 的元素 s

我已经尝试了以下

r = {}
for k, v in d.items():
    r[k] = [s for s in v if not any(s.endswith(val) for val in e)]  

我得到了

{'A1': ['john'], 'B1': ['hey']}

我的代码是删除以s 结尾的元素,例如'Tomas'

我想要的输出是以下内容,其中仅删除了 e 中的数字 + 元素,例如 3mm

{'A1': ['Tomas', 'john', 'Douglas'], 'B1': ['Tomm', 'Sterling', 'hey']}

如何更改代码以获得所需的输出?

【问题讨论】:

    标签: regex python-3.x list dictionary text


    【解决方案1】:

    也许,这可能接近你的想法,

    import re
    e = ['s', 'mm', 'ng']
    
    d = {'A1': ['Tomas',
                'john',
                '2s',
                'Douglas',
                '20ng'],
         'B1': ['Tomm',
                '3mm',
                'Sterling',
                'hey']}
    r = {}
    for k, v in d.items():
        r[k] = [s for s in v if not any(re.match(r'^[0-9]', s) for val in e)]
    
    print(r)
    

    输出

    {'A1': ['Tomas', 'john', 'Douglas'], 'B1': ['Tomm', 'Sterling', '嘿']}

    在这里,我们假设那些以数字开头的那些是不受欢迎的,然后找到那些使用,

    re.match(r'^[0-9]', s)
    

    并将其合并到您已经在列表理解中的if not 语句中。

    【讨论】:

    • 这将删除诸如4cm之类的字符串,但cm不是e的结尾
    【解决方案2】:

    如果您只想从e 中排除那些以数字和值结尾的值,您可以动态构建一个实现该值的正则表达式,例如

    \ds$
    

    \dng$
    

    我们可以使用与val 的字符串连接来构建它,然后在对re.search 的调用中使用它来确定值是否匹配:

    import re
    
    e = ['s', 'mm', 'ng']
    d = {'A1': ['Tomas', 
                'john',
     '2s',
     'Douglas',
        '20ng'],      
     'B1': ['Tomm',        
     '3mm',
     'Sterling',
           'hey']}
    r = {}
    for k, v in d.items():
        r[k] = [s for s in v if not any(re.search('\d' + val + '$', s) for val in e)]  
    print (r)
    

    输出:

    {'A1': ['Tomas', 'john', 'Douglas'], 'B1': ['Tomm', 'Sterling', 'hey']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 2020-05-13
      • 2017-10-09
      • 1970-01-01
      • 2017-07-02
      • 2022-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多