1 Python之基本数据类型

目录

从Hello World说起

1.1 Number类型

1.2 List类型

1.3 Tuple类型

1.4 String类型

1.5 Set类型

1.6 Dict类型

1.7 Boolean类型


Python是一种跨平台的计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发,本篇对PYTHON的基本语法进行学习。

从Hello World说起

输出一行HELLO WORLD:

>>> print('HELLO,WORLD')

HELLO,WORLD

在Python中,每个值都有一种数据类型,但和一些强类型语言不同,开发者不需要直接声明变量的数据类型。Python会根据每个变量的初始赋值分析其数据类型,并在内部进行跟踪,在Python中,内置的数据类型主要包含以下几种:

  • Number,数值类型;
  • String,字符串;
  • List,列表,一个包含元素的序列;
  • Tuple,元组,和列表相似,但其是不可变的;
  • Set,一个包含元素的集合,其中的元素是无序的;
  • Dict,字典,由键值对构成;
  • Boolean,布尔类型,值为True或False;
  • Byte,字节类型,例如一个以字节流表示的jpg文件;

1.1 Number类型

以number中的int类型为例,可以使用type关键字获取某个数据的类型:

>>> print(type(1))

<class 'int'>

>>> a = 1 + 2 // 3 ## // 表示整除

>>> print(type(a))

<class 'int'>

int和float之间,一般会通过是否有小数点进行区分:

>>> a = 2 ** 4

>>> print(a)

16

>>> print(type(a))

<class 'int'>

>>> b = 4.0

>>> print(b)

4.0

>>> print(type(b))

<class 'float'>

须注意的是,将一个int与一个int类型相加,将会得到int,但将int与float相加,将得到float,这是因为Python会把int强制转换为float后再进行加法运算:

>>> c = a + b

>>> print(c)

20.0

>>> print(type(c))

<class 'float'>

可以使用内置关键字进行int与float之间的强制转换:

>>> int_num = 100

>>> float_num = 200.02

>>> print(float(int_num))

100.0

>>> print(int(float_num))

200

如下是算数运算的示例:

>>> a , b , c = 1 , 2 , 3.0

>>> print(a+b)

3

>>> print(a-b)

-1

>>> print(a*b)

2

>>> print(a/b)

0.5

>>> print(a//b)

0

>>> print(a**b)

1

>>> print(b%a)

0

1.2 List类型

List,列表是可迭代对象,对于列表而言,序列中的每一个元素都在一个固定的位置(索引)上,索引从0开始,列表中的元素可以是任何数据类型,Python中列表对应的表示形式是[]。

>>> li = [1,2,3,4]

>>> print(li[0])

1

>>> print(li[1])

2

>>> print(li[-1])

4

列表切片(splice)可以简单描述为从列表中提取一部分元素的操作,即通过指定两个索引值,获取列表一部分数据,返回值也是一个列表,从第一个索引开始,直到第二个索引结束(不包括第二个索引的元素):

>>> li = [i for i in range(20)]

>>> print(li)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

>>> print(li[11])

11

>>> print(li[0:5])

[0, 1, 2, 3, 4]

>>> print(li[15:-1])

[15, 16, 17, 18]

>>> print(li[:5])

[0, 1, 2, 3, 4]

>>> print(li[::-1])

[19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

>>> l2 = li[:]

>>> print(l2)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

除了对列表进行切片外,还可以对列表进行插入、删除操作:

>>> li = ['a']

>>> print(li)

['a']

>>> li = li + ['b']

>>> print(li)

['a', 'b']

>>> li.append('c')

>>> print(li)

['a', 'b', 'c']

>>> li.insert(0,'x')

>>> print(li)

['x', 'a', 'b', 'c']

>>> print(len(li))

4

>>> li.insert(len(li),'y')

>>> print(len(li))

5

>>> print(li)

['x', 'a', 'b', 'c', 'y']

>>> li.append(['d','e'])

>>> print(li)

['x', 'a', 'b', 'c', 'y', ['d', 'e']]

>>>

>>> li.extend(['f','g'])

>>> print(li)

['x', 'a', 'b', 'c', 'y', ['d', 'e'], 'f', 'g']

其中,extend接收一个列表,并把其元素分别添加到原有列表中,类似于扩展,append是把参数作为一个元素整体添加到原有列表中,insert会将单个元素插入到列表中,其第一个参数是列表中将插入的位置。

>>> print(li)

['x', 'a', 'b', 'c', 'y', ['d', 'e'], 'f', 'g']

>>> del li[0]

>>> print(li)

['a', 'b', 'c', 'y', ['d', 'e'], 'f', 'g']

>>> li.append('a')

>>> print(li)

['a', 'b', 'c', 'y', ['d', 'e'], 'f', 'g', 'a']

>>> li.remove('a')

>>> print(li)

['b', 'c', 'y', ['d', 'e'], 'f', 'g', 'a']

>>> li.pop()

'a'

>>> print(li)

['b', 'c', 'y', ['d', 'e'], 'f', 'g']

>>> li.pop(0)

'b'

>>> print(li)

['c', 'y', ['d', 'e'], 'f', 'g']

其中,remove接收一个参数,并删除列表中第一次出现的该值,pop不带参数,将删除列表中的最后一个元素,并返回所删除的值,如果带参数,则删除指定的索引值。

1.3 Tuple类型

Tuple,元组,与列表非常相似,最大区别在于:元组不可修改,定义之后就固定了;元组用()括起来,由于元组不可修改,故不能插入和删除元素;其它操作和列表List类型相似。

>>> t1 = (1,2,3,4,5)

>>> print(t1)

(1, 2, 3, 4, 5)

>>> print(t1[3])

4

>>> print(t1.index(5))

4

1.4 String类型

创建字符串时,需以用引号括起来,可以使用单引号或双引号,字符串也是可迭代对象,可通过下标访问。

>>> str1 = 'I love python'

>>> print(str1)

I love python

>>> print(str1[0:3])

I l

>>> str1 = str1 + 'haha'

>>> print(str1)

I love pythonhaha

>>> str1 = str1 + ' gggg'*2

>>> print(str1)

I love pythonhaha gggg gggg

>>>

>>> str = '{0} like {1}'.format('Alen','Python') ##格式化

>>> print(str)

Alen like Python

>>> str = '''Hello ,world ! ##三个引号可输入多行

... I like python,

... what about you ?

... '''

>>> print(str)

Hello ,world !

I like python,

what about you ?



>>> str = 'i like python, what do you like ? like what ?'

>>> print(str.capitalize())

I like python, what do you like ? like what ?

>>> print(str.lower())

i like python, what do you like ? like what ?

>>> print(str.split())

['i', 'like', 'python,', 'what', 'do', 'you', 'like', '?', 'like', 'what', '?']

>>> print(str.upper())

I LIKE PYTHON, WHAT DO YOU LIKE ? LIKE WHAT ?

>>> print(str.startswith('i'))

True

>>> print(str.count('like'))

3

>>> print(str.find('like'))

2

>>> print(str.splitlines())

['i like python, what do you like ? like what ?']

1.5 Set类型

Set,集合特点时无序且值唯一,可以使用花括号{}或set()创建集合,要创建一个空集合,须使用set()。

>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

>>> print(basket)

{'pear', 'orange', 'banana', 'apple'}

>>> s1 = set()

>>> print(s1)

set()

>>> s1.add(10)

>>> print(s1)

{10}

>>> s1.add(7)

>>> print(s1)

{10, 7}

>>> s1.add(7)

>>> print(s1)

{10, 7}



>>> s1 = {1,2,3}

>>> l1 = [4,5,6]

>>> s2 = set(l1)

>>> print(s1)

{1, 2, 3}

>>> print(s2)

{4, 5, 6}

>>> s1.update(s2)

>>> print(s1)

{1, 2, 3, 4, 5, 6}

>>> s1.discard(4)

>>> print(s1)

{1, 2, 3, 5, 6}

>>> s1.remove(5)

>>> print(s1)

{1, 2, 3, 6}

>>> s1.discard(20) ##删除一个不存在的元素时,不出错

>>> s1.remove(20) ##删除一个不存在的元素时,出错

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 20

>>> s1.clear()

>>> print(s1)

set()

1.6 Dict类型

Dict,字典是键值对的无序集合,使用{}创建。

>>> d1 = {'a':1,'b':2}

>>> d2 = dict([['apple','fruit'],['lion','animal']])

>>> d3 = dict(name='Pairs',status='alive',location='SZ')

>>> print(d1)

{'a': 1, 'b': 2}

>>> print(d2)

{'apple': 'fruit', 'lion': 'animal'}

>>> print(d3)

{'name': 'Pairs', 'status': 'alive', 'location': 'SZ'}

>>>

>>> print(d1['a'])

1

>>> print(d3.get('name'))

Pairs

>>>

>>> d1['c']=3

>>> print(d1)

{'a': 1, 'b': 2, 'c': 3}

>>> d3.update(name='Alen',tel='110')

>>> print(d3)

{'name': 'Alen', 'status': 'alive', 'location': 'SZ', 'tel': '110'}

>>> del d1['c']

>>> print(d1)

{'a': 1, 'b': 2}

>>> d1.pop('a')

1

>>> print(d1)

{'b': 2}

>>> print(d3.keys())

dict_keys(['name', 'status', 'location', 'tel'])

>>> print(d3.values())

dict_values(['Alen', 'alive', 'SZ', '110'])

1.7 Boolean类型

Boolean,布尔类型,值包含True或False。

>>> print(1>2)

False

>>> print(1<2)

True

>>> print('Love' in 'I love SZ')

False

猜你喜欢

转载自blog.csdn.net/Alen_Liu_SZ/article/details/104221432