python数字、字符串、列表、元组

Python 数字运算

Python 解释器可以作为一个简单的计算器:您可以在解释器里输入一个表达式,它将输出表达式的值。
表达式的语法很直白: +, -, * 和/ 和在许多其它语言(如Pascal或C)里一样;括号可以用来为运算分组。例如:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # 总是返回一个浮点数
1.6

注意:在不同的机器上浮点运算的结果可能会不一样。之后我们会介绍有关控制浮点运算输出结果的内容。
在整数除法中,除法(/)总是返回一个浮点数,如果只想得到整数的结果,丢弃可能的分数部分,可以使用运算符 // :

>>> 17 / 3  # 整数除法返回浮点型
5.666666666666667
>>>
>>> 17 // 3  # 整数除法返回向下取整后的结果
5
>>> 17 % 3  # %操作符返回除法的余数
2
>>> 5 * 3 + 2
17

等号('=')用于给变量赋值。赋值之后,除了下一个提示符,解释器不会显示任何结果。

>>> width = 20
>>> height = 5*9
>>> width * height
900

Python 可以使用**操作来进行幂运算:

>>> 5 ** 2  # 5 的平方
25
>>> 2 ** 7  # 2的7次方
128

变量在使用前必须先"定义"(即赋予变量一个值),否则会出现错误:

>>> # 尝试访问一个未定义的变量
... n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

浮点数得到完全的支持;不同类型的数混合运算时会将整数转换为浮点数:

>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5

在交互模式中,最后被输出的表达式结果被赋值给变量 _ 。这能使您在把Python作为一个桌面计算器使用时使后续计算更方便,例如:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

此处, _ 变量应被用户视为只读变量。不要显式地给它赋值——这样您将会创建一个具有相同名称的独立的本地变量,并且屏蔽了这个内置变量的功能。

 

 

 

Python 字符串

除了数字,Python也能操作字符串。字符串有几种表达方式,可以使用单引号或双引号括起来:

>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

Python中使用反斜杠转义引号和其它特殊字符来准确地表示。
如果字符串包含有单引号但不含双引号,则字符串会用双引号括起来,否则用单引号括起来。对于这样的输入字符串,print() 函数会产生更易读的输出。
跨行的字面字符串可用以下几种方法表示。使用续行符,即在每行最后一个字符后使用反斜线来说明下一行是上一行逻辑上的延续:
以下使用 \n 来添加新行:

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.'  # \n 意味着新行
>>> s  # 不使用 print(), \n 包含在输出中
'First line.\nSecond line.'
>>> print(s)  # 使用 print(), \n 输出一个新行
First line.
Second line.

以下使用 反斜线(\) 来续行:

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
    Note that whitespace at the beginning of the line is\
 significant."

print(hello)

注意,其中的换行符仍然要使用 \n 表示——反斜杠后的换行符被丢弃了。以上例子将如下输出:

This is a rather long string containing
several lines of text just as you would do in C.
    Note that whitespace at the beginning of the line is significant.

或者,字符串可以被 """ (三个双引号)或者 ''' (三个单引号)括起来。使用三引号时,换行符不需要转义,它们会包含在字符串中。以下的例子使用了一个转义符,避免在最开始产生一个不需要的空行。

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")

其输出如下:

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to

如果我们使用"原始"字符串,那么 \n 不会被转换成换行,行末的的反斜杠,以及源码中的换行符,都将作为数据包含在字符串内。例如:

hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."

print(hello)

将会输出:

This is a rather long string containing\n\
several lines of text much as you would do in C.

字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复:

>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
''

两个紧邻的字面字符串将自动被串连;上例的第一行也可以写成 word = 'Help' 'A' ;这样的操作只在两个字面值间有效,不能随意用于字符串表达式中:

>>> 'str' 'ing'                   #  <- string="">>> 'str'.strip() + 'ing'   #  <- string="">>> 'str'.strip() 'ing'     #  <-  这样操作错误   File "", line 1, in ?
    'str'.strip() 'ing'
                      ^
SyntaxError: invalid syntax

字符串可以被索引;就像 C 语言一样,字符串的第一个字符的索引为 0。没有单独的字符类型;一个字符就是长度为一的字符串。就像Icon编程语言一样,子字符串可以使用分切符来指定:用冒号分隔的两个索引。

>>> word[4]
'A'
>>> word[0:2]
'Hl'
>>> word[2:4]
'ep'

默认的分切索引很有用:默认的第一个索引为零,第二个索引默认为字符串可以被分切的长度。

>>> word[:2]    # 前两个字符
'He'
>>> word[2:]    # 除了前两个字符之外,其后的所有字符
'lpA'

不同于C字符串的是,Python字符串不能被改变。向一个索引位置赋值会导致错误:

>>> word[0] = 'x'
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'str' object does not support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: 'str' object does not support slice assignment

然而,用组合内容的方法来创建新的字符串是简单高效的:

>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'

在分切操作字符串时,有一个很有用的规律: s[:i] + s[i:] 等于 s.

>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

对于有偏差的分切索引的处理方式也很优雅:一个过大的索引将被字符串的大小取代,上限值小于下限值将返回一个空字符串。

>>> word[1:100]
'elpA'
>>> word[10:]

>>> word[2:1]

在索引中可以使用负数,这将会从右往左计数。例如:

>>> word[-1]     # 最后一个字符
'A'
>>> word[-2]     # 倒数第二个字符
'p'
>>> word[-2:]    # 最后两个字符
'pA'
>>> word[:-2]    # 除了最后两个字符之外,其前面的所有字符
'Hel'
但要注意, -0 和 0 完全一样,所以 -0 不会从右开始计数!

>>> word[-0]     # (既然 -0 等于 0)
'H'

超出范围的负数索引会被截去多余部分,但不要尝试在一个单元素索引(非分切索引)里使用:

>>> word[-100:]
'HelpA'
>>> word[-10]    # 错误
Traceback (most recent call last):
  File "", line 1, in ?
IndexError: string index out of range

有一个方法可以让您记住分切索引的工作方式,想像索引是指向字符之间,第一个字符左边的数字是 0。接着,有n个字符的字符串最后一个字符的右边是索引n,例如:

+---+---+---+---+---+
 | H | e | l | p | A |
 +---+---+---+---+---+
 0   1   2   3   4   5
-5  -4  -3  -2  -1

第一行的数字 0...5 给出了字符串中索引的位置;第二行给出了相应的负数索引。分切部分从 i 到 j 分别由在边缘被标记为 i 和 j 的全部字符组成。
对于非负数分切部分,如果索引都在有效范围内,分切部分的长度就是索引的差值。例如, word[1:3] 的长度是2。
内置的函数 len() 用于返回一个字符串的长度:

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

 

 

 

Python 列表

Python囊括了大量的复合数据类型,用于组织其它数值。最有用的是列表,即写在方括号之间、用逗号分隔开的数值列表。列表内的项目不必全是相同的类型。

>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

像字符串一样,列表可以被索引和切片:

<pre>
>>> squares[0]  # 索引返回的指定项
1
>>> squares[-1]
25
>>> squares[-3:]  # 切割列表并返回新的列表
[9, 16, 25]

所有的分切操作返回一个包含有所需元素的新列表。如下例中,分切将返回列表 squares 的一个拷贝:

>>> squares[:]
[1, 4, 9, 16, 25]

列表还支持拼接操作:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Python 字符串是固定的,列表可以改变其中的元素:

>>> cubes = [1, 8, 27, 65, 125]   
>>> 4 ** 3  
64
>>> cubes[3] = 64  # 修改列表值
>>> cubes
[1, 8, 27, 64, 125]

您也可以通过使用append()方法在列表的末尾添加新项:

>>> cubes.append(216)  # cube列表中添加新值
>>> cubes.append(7 ** 3)  #  cube列表中添加第七个值
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

你也可以修改指定区间的列表值:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # 替换一些值
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # 移除值
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # 清楚列表
>>> letters[:] = []
>>> letters
[]

内置函数 len() 用于统计列表:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

也可以使用嵌套列表(在列表里创建其它列表),例如:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

 

Python3 元组

Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
如下实例:

tup1 = ('Google', 'CodingDict', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

创建空元组

tup1 = ();

元组中只包含一个元素时,需要在元素后面添加逗号

tup1 = (50,);

元组与字符串类似,下标索引从0开始,可以进行截取,组合等。

访问元组

元组可以使用下标索引来访问元组中的值,如下实例:

#!/usr/bin/python3

tup1 = ('Google', 'CodingDict', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

以上实例输出结果:

tup1[0]:  Google
tup2[1:5]:  (2, 3, 4, 5)

修改元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:

#!/usr/bin/python3

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz')

# 以下修改元组元素操作是非法的。
# tup1[0] = 100

# 创建一个新的元组
tup3 = tup1 + tup2;
print (tup3)

以上实例输出结果:

(12, 34.56, 'abc', 'xyz')

删除元组

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:

#!/usr/bin/python3

tup = ('Google', 'CodingDict', 1997, 2000)

print (tup)
del tup;
print ("删除后的元组 tup : ")
print (tup)

以上实例元组被删除后,输出变量会有异常信息,输出如下所示:

删除后的元组 tup :
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print (tup)
NameError: name 'tup' is not defined

元组运算符

与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组。

Python 表达式结果描述
len((1, 2, 3))3计算元素个数
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)连接
['Hi!'] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!']复制
3 in (1, 2, 3)True元素是否存在
for x in (1, 2, 3): print x,1 2 3迭代

元组索引,截取

因为元组也是一个序列,所以我们可以访问元组中的指定位置的元素,也可以截取索引中的一段元素,如下所示:
元组:

L = ('Google', 'Taobao', 'CodingDict')
Python 表达式结果描述
L[2]'CodingDict!'读取第三个元素
L[-2]'Taobao'反向读取;读取倒数第二个元素
L[1:]('Taobao', 'CodingDict!')截取元素,从第二个开始后的所有元素。

运行实例如下:

>>> L = ('Google', 'Taobao', 'CodingDict')
>>> L[2]
'CodingDict'
>>> L[-2]
'Taobao'
>>> L[1:]
('Taobao', 'CodingDict')

元组内置函数

Python元组包含了以下内置函数

序号方法及描述实例
1len(tuple)
计算元组元素个数。
>>> tuple1 = ('Google', 'CodingDict', 'Taobao')
>>> len(tuple1)
3
>>>
2max(tuple)
返回元组中元素最大值。
>>> tuple2 = ('5', '4', '8')
>>> max(tuple2)
'8'
>>>
3min(tuple)
返回元组中元素最小值。
>>> tuple2 = ('5', '4', '8')
>>> min(tuple2)
'4'
>>>
4tuple(seq)
将列表转换为元组。
>>> list1= ['Google', 'Taobao', 'CodingDict', 'Baidu']
>>> tuple1=tuple(list1)
>>> tuple1
('Google', 'Taobao', 'CodingDict', 'Baidu')

 

 

 

Python3 字典

字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
一个简单的字典实例:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

也可如此创建字典:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

访问字典里的值

把相应的键放入熟悉的方括弧,如下实例:

#!/usr/bin/python3

dict = {'Name': 'CodingDict', 'Age': 7, 'Class': 'First'}

print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

以上实例输出结果:

dict['Name']:  CodingDict
dict['Age']:  7

如果用字典里没有的键访问数据,会输出错误如下:

#!/usr/bin/python3

dict = {'Name': 'CodingDict', 'Age': 7, 'Class': 'First'};

print ("dict['Alice']: ", dict['Alice'])

以上实例输出结果:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print ("dict['Alice']: ", dict['Alice'])
KeyError: 'Alice'

修改字典

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

#!/usr/bin/python3

dict = {'Name': 'CodingDict', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8;               # 更新 Age
dict['School'] = "CodingDict教程"  # 添加信息


print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

以上实例输出结果:

dict['Age']:  8
dict['School']:  CodingDict教程

删除字典元素

能删单一的元素也能清空字典,清空只需一项操作。
显示删除一个字典用del命令,如下实例:

#!/usr/bin/python3

dict = {'Name': 'CodingDict', 'Age': 7, 'Class': 'First'}

del dict['Name'] # 删除键 'Name'
dict.clear()     # 删除字典
del dict         # 删除字典

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

但这会引发一个异常,因为用执行 del 操作后字典不再存在:

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptable

注:del() 方法后面也会讨论。

字典键的特性

字典值可以没有限制地取任何python对象,既可以是标准的对象,也可以是用户定义的,但键不行。
两个重要的点需要记住:
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:

#!/usr/bin/python3

dict = {'Name': 'CodingDict', 'Age': 7, 'Name': '编程高手'}

print ("dict['Name']: ", dict['Name'])

以上实例输出结果:

dict['Name']:  编程高手

2)键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行,如下实例:

#!/usr/bin/python3

dict = {['Name']: 'CodingDict', 'Age': 7}

print ("dict['Name']: ", dict['Name'])

以上实例输出结果:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'CodingDict', 'Age': 7}
TypeError: unhashable type: 'list'

字典内置函数&方法

Python字典包含了以下内置函数:

序号函数及描述实例
1len(dict)
计算字典元素个数,即键的总数。
>>> dict = {'Name': 'CodingDict', 'Age': 7, 'Class': 'First'}
>>> len(dict)
3
2str(dict)
输出字典以可打印的字符串表示。
>>> dict = {'Name': 'CodingDict', 'Age': 7, 'Class': 'First'}
>>> str(dict)
"{'Name': 'CodingDict', 'Class': 'First', 'Age': 7}"
3type(variable)
返回输入的变量类型,如果变量是字典就返回字典类型。
>>> dict = {'Name': 'CodingDict', 'Age': 7, 'Class': 'First'}
>>> type(dict)
<class 'dict'>

Python字典包含了以下内置方法:

序号函数及描述
1radiansdict.clear()
删除字典内所有元素
2radiansdict.copy()
返回一个字典的浅复制
3radiansdict.fromkeys()
创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4radiansdict.get(key, default=None)
返回指定键的值,如果值不在字典中返回default值
5key in dict
如果键在字典dict里返回true,否则返回false
6radiansdict.items()
以列表返回可遍历的(键, 值) 元组数组
7radiansdict.keys()
以列表返回一个字典所有的键
8radiansdict.setdefault(key, default=None)
和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9radiansdict.update(dict2)
把字典dict2的键/值对更新到dict里
10radiansdict.values()
以列表返回字典中的所有值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晓 5

有啥不懂的可以单聊解答....

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值