python数据问题
/Users/wangzhehan/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/2.0b4.0.9/6168c1e7e237bc1e5d434d11f98d27a4/Message/MessageTemp/9e20f478899dc29eb19741386f9343c8/Image/4921685501976_.pic_hd.jpg/Users/wangzhehan/Library/Containers/com.tencent.xinWeChat/Data/Library/Application Support/com.tencent.xinWeChat/2.0b4.0.9/6168c1e7e237bc1e5d434d11f98d27a4/Message/MessageTemp/9e20f478899dc29eb19741386f9343c8/Image/4931685501977_.pic_hd.jpg
请问一下各位,这两种获取在字典里的“value”,是有什么不同呢?或者说这两种获取方式 各有什么好处呢?@Dick_不周
第一种遍历的对象是dic.values(),第二种遍历了dic.items()
打印的时候都是打印的value,所以从结果上来看是没有区别的。
字典从3.6版本之后,遍历输出是按照插入的顺序来输出,所以两种方式输出顺序也一致。
至于哪种方式更好,你可以这么理解,
在只需要遍历value值得时候用第一种,
在需要根据key,value是否满足某个条件,例如value>1,'a' in key 时 更改value。或删除该键值对时第二种较好。
从运行效率上看,在低数据量时差异可忽略不计。
stu_list = [{"name": "zoey", "age": "18", "hobby": "eating"}, {"hobby1": "singing"}, {"hobby2": "sleeping"}]
res = [item[key] for item in stu_list for key in item]
print(res)
for item in stu_list:
for j, i in item.items():
print(j, i)
运行结果:
['zoey', '18', 'eating', 'singing', 'sleeping']
name zoey
age 18
hobby eating
hobby1 singing
hobby2 sleeping