Python基础01 集合
初始化
# python3 # coding = utf-8 mylist = [] for item in range(10): mylist.append(item * 10 + 3) myset = set() for item in range(10): myset.add('key{}'.format(item)) mytuple = () mytuple = mytuple + (1,) print(mytuple) mytuple = mytuple + tuple(mylist) print(mytuple) mydict = {} for item in range(10): mydict['key{}'.format(item)] = item print('dict initialize with -1:') mydict = {}.fromkeys(('x', 'y'), -1) print(mydict)
迭代
for item in mylist: print(item) for index in range(len(mylist)): print('index:', index, 'item:', mylist[index]) for index, item in enumerate(mylist): print('index:', index, 'item:', item)
迭代时删除
mylist[:] = [item for item in mylist if item % 2 == 0] # remove dict item while iterating # in python2, just for key in mydict.keys() for key in list(mydict.keys()): if mydict[key] % 2 == 0: del mydict[key]
参考文献