python基础2—集合框架

详细的,比较深入的,比如集合容量初始化,扩容, 目前只是学到基础的用法。 

 ------------------list-------------------- #
li = [1,2,3, '456', [1,2,3], {1:'one', 2:'two'}]
print(type(list))       
print(type(li))         # list

print(li[0])
print(li[-1])
print(li[-2])

# find index of element
print(li.index('456'))
print(li.index([1,2,3]))
print(li.index(-1)
del(li[-1])  #delete element del(list[index]) 

# add element
l_a = [1, 2, 3]
l_a.append(4)
l_a.append(5)
l_b = [6, 7, 8] 
l_a.extend(l_b)     # extend会展开再一个一个的添加
l_a.append(l_b)   #  append 会将其视为一个对象
print(l_a)              # will be [1, 2, 3, 4, 5, 6, 7, 8]

l_a = []
if not l_a:
    print('Empty')  # empty 有内存分配 
    pass
if l_a is None:
    print('None')   # None 无内存分配
    pass

# for loop
for i in li:
    print(i)
    pass
for i in range(len(li)):
    print(i)
    pass

# ------------------dict-------------------- #
d = {'a':1, 'b':2, 1:'one', 2:'two', 3:[1,2,3]}
print(type(dict))
print(type(d))
print(d)

# # access element
print(d['a'])
print(d[1])
print(d[3])

# key is exist
print('two' in d)
print(3 in d)
del(d[3])   # del(dict[key])
d[3] = [1, 2, 3, 4]       # add or update element when key=3
d['a'] = '1234'           # add or update element when key='a'

print(len(d))

# ------------------set-------------------- #
s_a = set([1, 2, 2, 3, 4, 5, 6])
s_b = set([4, 5, 6, 7, 8, 9])
print(s_a)
print(s_b)

# element is exist
print(5 in s_a)
print(10 in s_b)

# 并集   A | B  =>  A.unio(B)
print(s_a | s_b)
print(s_a.union(s_b))

# 交集    A & B  =>  A.intersection(B)
print(s_a & s_b)
print(s_a.intersection(s_b))

# 差集    A - B = A - (A & B)   =>   A.difference(B)
print(s_a - s_b)
print(s_a.difference(s_b))

# 对称差  (A | B ) - (A & B)     =>   A.symmetric_difference(B)
print(s_a ^ s_b)
print(s_a.symmetric_difference(s_b))

# add or modify element
s_a.add('x')
s_a.update([4, 5, 60, 70])   # add array to set
print(s_a)

s_a.remove(70)
print(s_a)
print(len(s_a))

for x in s_a:
    print(x)
    pass

 

posted @ 2018-01-22 16:08  zeroonec  阅读(238)  评论(0编辑  收藏  举报