【参考:极客时间陈旸——数据分析实战45讲】
数据类型:列表、元组、字典和集合
1.列表
lists = ['a','b','c']
lists.append('d')
print lists
print len(lists)
lists.insert(0,'mm')
lists.pop()
print lists
运行结果:
['a', 'b', 'c', 'd']
4
['mm', 'a', 'b', 'c']
列表相当于数组,具有增删改查的功能。可用len()获得lists中元素个数,append()在尾部添加元素,insert()插入元素,pop()删除尾部的函数。
2.元组(tuple)
tuples = ('tupleA','tupleB')
print tuples[0]
运行结果:
tupleA
元组和列表类似,但元组不能修改。
3.字典{dictionary}
# -*- coding: utf-8 -*
# 定义一个 dictionary
score = {'guanyu':95,'zhangfei':96}
# 添加一个元素
score['zhaoyun'] = 98
print score
# 删除一个元素
score.pop('zhangfei')
# 查看 key 是否存在
print 'guanyu' in score
# 查看一个 key 对应的值
print score.get('guanyu')
print score.get('yase',99) #如果查询的值不存在,可以给一个默认值
运行结果:
{'guanyu': 95, 'zhaoyun': 98, 'zhangfei': 96}
True
95
99
4. 集合
s = set(['a', 'b', 'c'])
s.add('d')
s.remove('b')
print s
print 'c' in s
运行结果:
set(['a', 'c', 'd'])
True
集合set与字典类似,只不过集合是key的集合,不存储view。
集合可删(remove)可加(add)。