📜  Python – 从字典字符串值列表中删除数字

📅  最后修改于: 2022-05-13 01:55:20.784000             🧑  作者: Mango

Python – 从字典字符串值列表中删除数字

给定具有字符串列表值的字典列表,从所有字符串中删除所有数字。

方法:使用正则表达式+字典理解

这个问题可以通过结合使用这两种功能来解决。在此,我们应用正则表达式将每个数字替换为空字符串,并使用字典理解编译结果。

Python3
# Python3 code to demonstrate working of 
# Remove digits from Dictionary String Values List
# Using loop + regex() + dictionary comprehension 
import re
  
# initializing dictionary
test_dict = {'Gfg' : ["G4G is Best 4", "4 ALL geeks"],
             'is' : ["5 6 Good"], 
             'best' : ["Gfg Heaven", "for 7 CS"]} 
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# using dictionary comprehension to go through all keys
res = {key: [re.sub('\d', '', ele) for ele in val]
       for key, val in test_dict.items()}
          
# printing result 
print("The filtered dictionary : " + str(res))


输出
The original dictionary is : {'Gfg': ['G4G is Best 4', '4 ALL geeks'], 'is': ['5 6 Good'], 'best': ['Gfg Heaven', 'for 7 CS']}
The filtered dictionary : {'Gfg': ['GG is Best ', ' ALL geeks'], 'is': ['  Good'], 'best': ['Gfg Heaven', 'for  CS']}