009整型、浮点型、字符串型、列表型、字典型、布尔型

整型、浮点型、字符串型、列表型、字典型、布尔型


一、整型(int)


1.1作用

表示人的年龄、各种号码、级别


1.2定义

age = 18  # age=int(18)

print(id(age))
print(type(age))
print(age)

输出结果:

4530100848
<class 'int'>
18

1.3 如何用

加减乘除、逻辑判断(大于、小于)


二、浮点型(float)


2.1 作用

表示身高、体重、薪资


2.2 定义

salary = 2.1  # salary=float(2.1)

print(id(salary))
print(type(salary))
print(salary)

输出结果:

4569240656
<class 'float'>
2.1

2.3 如何用

加减乘除、逻辑判断(大于、小于)


字符串类型


三、字符串(str)

3.1作用

表示名字、爱好

3.2 定义

字符串相当于一根羊肉串。而字符串就是一串被串起来的字符,在单引号、双引号或三引号内包裹的一串字符。需要注意的是:三引号内的字符可以换行,而单双引号内的字符不行。

name1 = 'frist'
name2 = "reed"
print(id(name1))
print(type(name1))
print(name1)

输出结果:

4418849624
<class 'str'>
first
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

3.3字符串的序号(索引Index)


正向递增序号和反向递减序号


+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0   1   2   3   4   5   6(---->正向递增序号)
-6  -5  -4  -3  -2  -1(<-------反向递减序号)注意 -0 和 0 是一样的,所以负数索引从 -1 开始。
word='python'
print(x[5])
print(x[-6])

输出结果:

n
p

注意 -0 和 0 是一样的,所以负数索引从 -1 开始。

3.4切片

除了索引,字符串还支持 切片。索引可以得到单个字符,而 切片 可以获取子字符串:


>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

注意切片的开始总是被包括在结果中,而结束不被包括。这使得 s[:i] + s[i:] 总是等于 s

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

切片的索引有默认值;省略开始索引时默认为0,省略结束索引时默认为到字符串的结束:

>>> word[:2]   # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]   # characters from position 4 (included) to the end
'on'
>>> word[-2:]  # characters from the second-last (included) to the end
'on'

使用过大的索引会产生一个错误:

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

但是,切片中的越界索引会被自动处理:

>>> word[4:42]
'on'
>>> word[42:]
''

Python 中的字符串不能被修改,它们是 immutable 的。因此,向字符串的某个索引位置赋值会产生一个错误:

>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

如果需要一个不同的字符串,应当新建一个:

>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

3.4内建函数len()


返回字符串的长度


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

3.4如何用

字符串只能+、*和逻辑比较

字符串的拼接,即重新申请一个小空间把两个字符串都拷贝一份后再拼接。而不是你YY的把一个小空间内的变量值复制到另一个变量的小空间内,然后拼接。

>>> msg2 = "my name is 'reed'"
>>> msg3 = 'my name is "reed"'

>>> print(msg2 + msg3)   
'my name is 'reed'my name is "reed"'

注意:如果字符串内有引号,则包裹字符串的引号和字符串内部的引号不能相同。

>>> name = 'reed '
>>> print(name * 3)
reed  reed reed

注意:字符串的乘法只能乘以数字。

>>> msg1 = 'hello'
>>> msg2 = 'z'
>>> print(msg1 > msg2)
False

注意:字符串比较大小,按照ASCII码比较,以后会细讲。

>>> msg3 = 'zero'
>>> msg4 = 'zx'

>>> print(msg3 > msg4)
>>> print('Z' > 'A')
>>> print('Z' > 'a')
False
True
False

注意:字符串的比较是字母的顺序。

参见

4、列表

4.1作用


Python 中可以通过组合一些值得到多种 复合 数据类型。其中最常用的 列表 ,可以通过方括号括起、逗号分隔的一组值得到。一个 列表 可以包含不同类型的元素,但通常使用时各个元素类型相同:

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

4.2 如何用

和字符串(以及各种内置的 sequence 类型)一样,列表也支持索引和切片:

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

所有的切片操作都返回一个包含所请求元素的新列表。 这意味着以下切片操作会返回列表的一个 浅拷贝:

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

列表同样支持拼接操作:

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

immutable 的字符串不同, 列表是一个 mutable 类型,就是说,它自己的内容可以改变:

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

你也可以在列表结尾,通过 append() 方法 添加新元素 (我们会在后面解释更多关于方法的内容):

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

给切片赋值也是可以的,这样甚至可以改变列表大小,或者把列表整个清空:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> 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'

5、字典

5.1作用

另一个非常有用的 Python 內置数据类型是 字典 (参见 映射类型 --- dict)。字典在其他语言里可能会被叫做 联合内存联合数组。与以连续整数为索引的序列不同,字典是以 关键字 为索引的,关键字可以是任意不可变类型,通常是字符串或数字。如果一个元组只包含字符串、数字或元组,那么这个元组也可以用作关键字。但如果元组直接或间接地包含了可变对象,那么它就不能用作关键字。列表不能用作关键字,因为列表可以通过索引、切片或 append()extend() 之类的方法来改变。


5.2如何用


理解字典的最好方式,就是将它看做是一个 键: 值 对的集合,键必须是唯一的(在一个字典中)。一对花括号可以创建一个空字典:{} 。另一种初始化字典的方式是在一对花括号里放置一些以逗号分隔的键值对,而这也是字典输出的方式。

>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}

字典主要的操作是使用关键字存储和解析值。也可以用 del 来删除一个键值对。

>>> del tel['sape']
>>> tel
{'jack': 4098, 'guido': 4127}

如果你使用了一个已经存在的关键字来存储值,那么之前与这个关键字关联的值就会被遗忘。用一个不存在的键来取值则会报错。

>>> tel['jack'] = 4127
>>> tel
{'jack': 4127, 'guido': 4127}

对一个字典执行 list(d) 将返回包含该字典中所有键的列表.

>>> list(tel)
['jack', 'guido', 'irv']

按插入次序排列 (如需其他排序,则要使用 sorted(d))。

>>> sorted(tel)
['guido', 'irv', 'jack']

要检查字典中是否存在一个特定键,可使用 in 关键字。

>>> 'guido' in tel
True
>>> 'jack' not in tel
False

dict() 构造函数可以直接从键值对序列里创建字典。

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'guido': 4127, 'jack': 4098}

此外,字典推导式可以从任意的键值表达式中创建字典

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

当关键字是简单字符串时,有时直接通过关键字参数来指定键值对更方便

 dict(sape=4139, guido=4127, jack=4098)
{'sape': 4139, 'guido': 4127, 'jack': 4098}

6.布尔值

6.1 作用

用于判断条件结果

6.2 定义

True、False通常情况不会直接引用,需要使用逻辑运算得到结果。

6.3 如何用

>>>print(type(True))
<class 'bool'>
>>>print(True)
True

注意:Python中所有数据类型的值自带布尔值。如此多的数据类型中只需要记住只有0、None、空、False的布尔值为False,其余的为True。

>>>print(bool(0))
False
>>>print(bool(None))
False
>>>print(bool(''))
False
>>>print(bool([]))
False
>>>print(bool({}))
False
>>>print(bool(False))
False

猜你喜欢

转载自www.cnblogs.com/FirstReed/p/11729517.html