S.no Name Expected Result
------ ---------------------- ----------------------
1 2341 blvd 2341 Boulevard
2 648 s Kingston rd 648 S Kingston Road
3 sw Beverly st SW Beverly Street
def wordreplace(s, d):
"""Replaces words in string by dict d. # Thank you @Patrick Artner
for improving dict call to d.get(w, w)!"""
return ' '.join([ d.get(w, w) for w in s.split()])
# this was my old version:
# def wordreplace(s, d):
# """Replaces words in string by dict d."""
# return ' '.join([ d[w] if w in d else w for w in s.split()])
d = {'blvd': 'Boulevard', 'st': "Street", 'sw': 'SW', 's': "S", 'rd': '
Road'}
s1 = "2341 blvd"
s2 = "648 s Kingston rd"
s3 = "sw Beverly st"
wordreplace(s1, d)
# '2341 Boulevard'
wordreplace(s2, d)
# '648 S Kingston Road'
wordreplace(s3, d)
# 'SW Beverly Street'
默认情况下,s.split()按单个空格分隔,因此返回字符串s的单词列表。每个单词都加载到变量w中。列表表达式的for w in s.split()部分。
在for之前的部分确定在结果列表中收集的内容。你知道吗
if w in d意思是:测试单词是否在给定的替换词典中d。它查看d.keys()字典的键。找到时,它返回字典值d[w]。else它返回单词本身w。你知道吗
结果列表是使用' '作为连接元素的join,因此单词列表被重新转换为字符串。你知道吗
列表表达式非常方便,常常导致这样的单行函数。所以强烈建议你去学习。你知道吗
除了在字典表单中键入所有键值之外,您还可以执行以下操作:
keys = [ # list here all keys ]
vals = [ # list here all corresponding values in the right order ]
d = {k: vals[i] for i, k in enumerate(keys)}
同样,您可以使用列表表达式的功能来生成字典。你知道吗
# abstract it to a function
def lists2dict(keys_list, vals_list):
return {k, vals_list[i] for i, k in enumerate(key_list)}
# and then call:
d = lists2dict(keys, vals)
默认情况下,
s.split()
按单个空格分隔,因此返回字符串s的单词列表。每个单词都加载到变量w中。列表表达式的for w in s.split()
部分。 在for
之前的部分确定在结果列表中收集的内容。你知道吗if w in d
意思是:测试单词是否在给定的替换词典中d
。它查看d.keys()
字典的键。找到时,它返回字典值d[w]
。else
它返回单词本身w
。你知道吗结果列表是使用
' '
作为连接元素的join
,因此单词列表被重新转换为字符串。你知道吗列表表达式非常方便,常常导致这样的单行函数。所以强烈建议你去学习。你知道吗
除了在字典表单中键入所有键值之外,您还可以执行以下操作:
同样,您可以使用列表表达式的功能来生成字典。你知道吗
相关问题 更多 >
编程相关推荐