[关闭]
@Channelchan 2017-11-21T19:09:22.000000Z 字数 1790 阅读 137393

Python数据类型

- 数字(Number)

最常用的数字类型包括整型数(int),浮点型(float),正负数皆可。

整数型(int)

  1. a=666
  2. type(a)
int

浮点型(float)

  1. b=-6.66
  2. type(b)
float

布尔值(Boolean)

主要用于判断真假,True代表真,False代表假。

  1. i=1
  2. i>0
True
  1. i<0
False

- 序列(有顺序)

字符串

字符串或串(String)是由数字、字母、下划线组成的一串字符。用引号限制起来。

  1. string='大鱼金融是你身边No_1的Quantitative Trader'
  1. string[0:4]
'大鱼金融'

元组

提醒:Python默认索引的起始值为0,不为1。

元组是一系列Python数据类型安装顺序组成的序列。用小括号表征。报错由于元组内容不可变。

  1. t=(6,'abc',0.1)
  1. t[0]
6
  1. t[1]
'abc'
  1. t[0]=666
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-10-b98c09a85d62> in <module>()
----> 1 t[0]=666


TypeError: 'tuple' object does not support item assignment

列表

列表和元组功能上类似,但表达方法不同,列表用[]表示。列表内容可修改。

  1. l = [6,'abc',0.1]
  1. l[0]
6
  1. l[0]=666
  2. l
[666, 'abc', 0.1]

- 映射 (键值对应,无序)

字典

字典是非常实用的数据结构,它包括了多组键(Key):值(Value)。字典用{}表示。

  1. d={}
  2. d['microsoft']=100
  3. d['apple']= 150
  4. d['google']=200
  1. d
{'apple': 150, 'google': 200, 'microsoft': 100}
  1. d['apple']
150
  1. d.keys()
dict_keys(['microsoft', 'apple', 'google'])
  1. d.values()
dict_values([100, 150, 200])
  1. d.get('apple')
150
  1. # 修改
  2. d['apple'] = 50
  3. d
{'apple': 50, 'google': 200, 'microsoft': 100}
  1. # 删除
  2. del d['apple']
  3. d
{'google': 200, 'microsoft': 100}
  1. # 添加字典
  2. d.update({'apple':50})
  3. d
{'apple': 50, 'google': 200, 'microsoft': 100}
  1. # pop删除
  2. d.pop('apple')
50
  1. d
{'google': 200, 'microsoft': 100}
  1. for k,v in d.items():
  2. print (k)
microsoft
google

集合

函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。

  1. x = set('apple')
  2. y = set('google')
  3. z = set([0,0,0,1,1,1,2,1,3,4,5,6,5,6,6])
  1. #无序去重
  2. x
{'a', 'e', 'l', 'p'}
  1. y
{'e', 'g', 'l', 'o'}
  1. z
{0, 1, 2, 3, 4, 5, 6}
  1. # 交集
  2. x&y
{'e', 'l'}
  1. # 并集
  2. x|z
{0, 1, 2, 3, 4, 'l', 5, 6, 'a', 'e', 'p'}
  1. # 差集
  2. x-y
{'a', 'p'}

- 数据转换

  1. t = (1,2,3,4,5,6,6,6,6)
  1. list(t)
[1, 2, 3, 4, 5, 6, 6, 6, 6]
  1. tuple(t)
(1, 2, 3, 4, 5, 6, 6, 6, 6)
  1. set(t)
{1, 2, 3, 4, 5, 6}
  1. keys = list(set(t))
  1. values = ['a','b','c','d','e','f', 'g']

zip()

函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。

  1. list(zip(keys, values))
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')]
  1. dict(zip(keys, values))
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f'}
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注