Python – 从字典字符串值列表中删除数字
给定具有字符串列表值的字典列表,从所有字符串中删除所有数字。
Input : test_dict = {‘Gfg’ : [“G4G is Best 4”, “4 ALL geeks”], ‘best’ : [“Gfg Heaven”, “for 7 CS”]}
Output : {‘Gfg’: [‘GG is Best ‘, ‘ ALL geeks’], ‘best’: [‘Gfg Heaven’, ‘for CS’]}
Explanation : All the numeric strings are removed.
Input : test_dict = {‘Gfg’ : [“G4G is Best 4”, “4 ALL geeks”]}
Output : {‘Gfg’: [‘GG is Best ‘, ‘ ALL geeks’]}
Explanation : All the numeric strings are removed.
方法:使用正则表达式+字典理解
这个问题可以通过结合使用这两种功能来解决。在此,我们应用正则表达式将每个数字替换为空字符串,并使用字典理解编译结果。
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']}