为了举一反三,多种方式尝试解决问题。
将列表[11, 22, 33, 44, 55, 66, 77, 88, 99]按大于66的存储在k1里,其余的存储在k2里。
本次的环境是在windows7下,我的python是python3.4.3
方法1:
也是接触python开始最先想到的,中规中矩的做法
# -*- encoding = utf-8 -*-
all_items = [11, 22, 33, 44, 55, 66, 77, 88, 99]
def dictSort():
dic = dict()
# loop
for value in all_items:
if value > 66:
if "k1" in dic.keys():
dic["k1"].append(value)
else:
dic["k1"] = [value]
else:
if "k2" in dic.keys():
dic["k2"].append(value)
else:
dic["k2"] = [value]
print(dic)
if __name__ == '__main__':
dictSort()
{'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99]}
第一次写好代码后,调试发现有问题,
dic["k2"] = value
写成了这样,而实际dic["key"]是一个list,赋值方式不对导致出错了。
方法2
借助setdefault()
# -*- encoding = utf-8 -*-
all_items = [11, 22, 33, 44, 55, 66, 77, 88, 99]
def dictSortBysetdefault():
dic = dict()
# loop list
for value in all_items:
if value >66:
dic.setdefault("k1", []).append(value)
else:
dic.setdefault("k2", []).append(value)
print(dic)
if __name__ == '__main__':
dictSortBysetdefault()
{'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99]}
方法2调试时,根据setdefault的API说明,D.setdefault(k[,]),看这写法以为[]是可以省略的,就写成了
dic.setdefault("k1").append(value)
结果出错了。
方法3
使用collections.defaultdict().
# -*- encoding = utf-8 -*-
import collections
all_items = [11, 22, 33, 44, 55, 66, 77, 88, 99]
def defDictSort():
dic = collections.defaultdict(list)
# loop list
for value in all_items:
if value >66:
dic["k1"].append(value)
else:
dic["k2"].append(value)
print(dic)
if __name__ == '__main__':
defDictSort()
defaultdict(, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99]})
定义字典变量的时候,原来还要指定values的属性,最开始写成了下面这样
dic = collections.defaultdict()
方法4:
使用D.fromkeys()生成一个“默认”的字典。然后根据条件再去追加values.
# -*- encoding = utf-8 -*-
import collections
all_items = [11, 22, 33, 44, 55, 66, 77, 88, 99]
def dictByFromKeys():
dic = {}.fromkeys(("k1", "k2"))
# get values by loop list
for value in all_items:
if value > 66:
if dic["k1"] is None:
dic["k1"] = [value]
else:
dic["k1"].append(value)
else:
if dic["k2"] is None:
dic["k2"] = [value]
else:
dic["k2"].append(value)
print(dic)
if __name__ == '__main__':
dictByFromKeys()
{'k1': [77, 88, 99], 'k2': [11, 22, 33, 44, 55, 66]}
代码写完调试的时候,fromkeys()默认的value是None,上来拿到list的元素后就直接判断append了,导致报错:NoneType 没有append属性。
然后间接转换了一下,先去判断是否为None,如果是就直接赋值,如果不是,那证明已经有数据加入了,然后再使用append方法就没问题了。
方法5
借助defaultdict跟set,但缺点是,values是无序的。
# -*- encoding = utf-8 -*-
import collections
all_items = [11, 22, 33, 44, 55, 66, 77, 88, 99]
def dictBySet():
dic = collections.defaultdict(set)
# loop list
for value in all_items:
if value > 66:
dic["k1"].add(value)
else:
dic["k2"].add(value)
print(dic)
if __name__ == '__main__':
dictBySet()
defaultdict(, {'k1': {88, 99, 77}, 'k2': {33, 66, 11, 44, 22, 55}})
--- over ---