这里有没有人有任何有用的代码在python中使用reduce()函数?除了我们在示例中看到的通常的+和*之外,还有其他代码吗?
通过GvR 参考Python 3000中的reduce()命运
对于大量嵌套字典,我想检查它们是否包含密钥.它们中的每一个都可能有也可能没有嵌套字典之一,所以如果我循环搜索所有这些字典会引发错误:
for Dict1 in DictionariesList:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
Run Code Online (Sandbox Code Playgroud)
我目前的解决方案是:
for Dict1 in DictionariesList:
if "Dict2" in Dict1:
if "Dict3" in Dict1['Dict2']:
if "Dict4" in Dict1['Dict2']['Dict3']:
print "Yes"
Run Code Online (Sandbox Code Playgroud)
但这是令人头痛的,丑陋的,可能不是非常有效的资源.这是以第一种方式执行此操作的正确方法,但在字典不存在时不会引发错误?
我想找到一个更好的方法来实现这个:
d = {"a": {"b": {"c": 4}}}
l = ["a", "b", "c"]
for x in l:
d = d[x]
print (d) # 4
Run Code Online (Sandbox Code Playgroud)
我正在学习函数式编程,所以我只是尝试随机的例子来到我脑海里:)
假设你有一个清单
a = [3,4,1]
Run Code Online (Sandbox Code Playgroud)
我想用这些信息指向字典:
b[3][4][1]
Run Code Online (Sandbox Code Playgroud)
现在,我需要的是例程.在我看到值之后,在b的位置读取和写入一个值.
我不喜欢复制变量.我想直接更改变量b的内容.
我有一个深嵌套的dict(从json解码,来自instagram api).我的初始代码是这样的:
caption = post['caption']['text']
Run Code Online (Sandbox Code Playgroud)
但是如果'caption'键或'text'键不存在,那将抛出NoneType或KeyError错误.
所以我想出了这个:
caption = post.get('caption', {}).get("text")
Run Code Online (Sandbox Code Playgroud)
哪个有效,但我不确定它的风格.例如,如果我将此技术应用于我正在尝试检索的更深层次的嵌套属性之一,它看起来非常难看:
image_url = post.get('images',{}).get('standard_resolution',{}).get('url')
Run Code Online (Sandbox Code Playgroud)
有没有更好,更pythonic的方式来写这个?我的目标是检索数据(如果有的话),但如果数据不存在则不会阻止执行.
谢谢!
我需要从一些大的嵌套字典中获取一些值.出于懒惰,我决定编写一个递归调用自身的函数,直到找到最后一个子元素,或者叶子为空.
由于有字典弹出,每次新调用都有一个新的字典,我想知道它有多高效.
有什么建议?
def recursive_dict_get(item, string, default=False):
if not isinstance(item, dict):
return default
print "called with ", item, "and string", string
if "." in string:
attrs = string.split(".")
parent = attrs.pop(0)
rest = ".".join(attrs)
result = item.get(parent, None)
if result is None:
return default
else:
return recursive_dict_get(item.get(parent, default), rest, default)
else:
return item.get(string, default)
Run Code Online (Sandbox Code Playgroud)
foo = {
"1": {
"2": {
"3": {
"4":{
"5": {
"6": {
"7": "juice"
}
}
}
}
}
}
}
print recursive_dict_get(foo, …Run Code Online (Sandbox Code Playgroud) python ×6
dictionary ×3
keyerror ×1
nested ×1
nonetype ×1
python-2.6 ×1
python-2.7 ×1
python-2.x ×1
styles ×1