[英]List comprehension, but for dictionaries?
执行以下操作的更Python方式? 在此示例中,我尝试将注释(字典)构建为键-值对,其中键是未修改版本,并且值是键作为arg传递的函数的返回值。
def func(word):
return word[-1:-6:-1].upper()
subs = {
'ALLOWED': ['one', 'two'],
'DISALLOWED': ['three', 'four']
}
comments = {}
for sub in subs['ALLOWED']:
# reverse and uppercase
comments[sub] = func(sub)
print(comments)
有人推荐吗? 做到这一点并不完全重要,但是我喜欢学习python习惯用法和使我的代码更具pythonic的方法。 谢谢!
使用dict理解而不是在for
循环中构建字典:
comments = {key: func(key) for key in subs['ALLOWED']}
删除循环,并用字典理解将其替换为函数。 然后,您可以简单地将其返回。
另外,您可以使用[::-1]
而不是正在使用的复杂[-1:-6:-1]
片来反转字符串word
:
def func(words):
return {word: word[::-1].upper() for word in words}
这将产生相同的结果:
comments = func(subs['ALLOWED'])
print(comments)
# {'two': 'OWT', 'one': 'ENO'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.