Data Types and operation
- Python 赋值方式
x = 2
y = 3
z = 5
x,y,z = 2,3,5
- python 支持自操作运算符
#variables.py
reservoir_volume = 4.445e8
rainfall = 5e6
rainfall -= rainfall*0.1
reservoir_volume += rainfall
reservoir_volume += reservoir_volume*0.05
reservoir_volume -= reservoir_volume*0.05
reservoir_volume -= 2.5e5
print(reservoir_volume)
- python 可格式化输出
print('The num is %.2f',%(1.11+2.22))
>>> format(math.pi, '.12g') # give 12 significant digits
'3.14159265359'
>>> format(math.pi, '.2f') # give 2 digits after the point
'3.14'
>>> repr(math.pi)
'3.141592653589793'
- python 类型检查
#每一个对象都是一个类型
#对象类型定义了哪些运算符和函数适合该对象以及计算原理
#type()得到一个对象的类型
print(type(crs_per_rab))
- 数据类型转换
#初始浮点数赋值
f_ex1 = 383.
f_ex2 = 383.0
#数据类型转换
x = int(4.7) # x is now an integer 4
y = float(4) # y is now a float of 4.0
Tip
print(0.1+0.1+0.1)
>> 0.30000000000000004
出现上面情况的原因是我们使用的数制均为10进制,但是计算机表示类型是2进制,就比如1/3用10进制只能近似的表示一样,大部分数10进制小数也只能由2进制近似表示,比如0.1
存在多个数转换为二进制存储在机器中时,近似于一个值.
0.1 and 0.10000000000000001 and 0.1000000000000000055511151231257827021181583404541015625 are all approximated by 3602879701896397 / 2 ** 55.
所以有
>>> .1 + .1 + .1 == .3
False
>>> round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1)
False
>>> round(.1 + .1 + .1, 10) == round(.3, 10)
True
Boolean 布尔运算
True or False
- 运算
- and 与
- or 或
- not 非
String
#''内可以无须用转义字符就正常显示字符串内的双引号
#如果''和''''都有,利用/转义
#
-
- 连接字符串
-
- 重复字符串
- lower()
first_world = 'hello'
second_word = 'world'
print(first_world + ' ' + second_word)
word = '9'
word *= 5
len(word)
sample_string.lower()
# Example 1
>>> print("Mohammed has {} balloons".format(27))
Mohammed has 27 balloons
# Example 2
>>> # Example 2
>>> animal = "dog"
>>> action = "bite"
>>> print("Does your {} {}?".format(animal, action))
Does your dog bite?
# Example 3
maria_string = "Maria loves {} and {}"
print(maria_string.format("math","statistics"))
Maria loves math and statistics
- split()
- 返回一个list,其中包含字符串中所有被分割后的单词
- separator:给定该参数,按给出字符进行分割
- maxsplit: 给定该参数,返回一个list,长度为maxsplit+1,最后一个是剩余字符串
new_str = "The cow jumped over the moon."
new_str.split()
new_str.split(' ', 3)
new_str.split('.')
new_str.split(None, 3)
[‘The’, ‘cow’, ‘jumped’, ‘over the moon.’]
[‘The’, ‘cow’, ‘jumped’, ‘over the moon.’]
[‘The cow jumped over the moon’, ‘’]
[‘The’, ‘cow’, ‘jumped’, ‘over the moon.’]
扫描二维码关注公众号,回复: 6124032 查看本文章
List
- List
- list是有序的
- 与其他高级语言不同,python支持在一个list中包含许多数据类型
- 用[中括号]声明和创建
list_of_random_things = [1, 3.4, 'a string', True]
- 与其他高级语言不同,list支持通过负数index进行随机访问,其为倒数位置
>>> list_of_random_things[-1]
True
>>> list_of_random_things[-2]
a string
- 操作与运算
- 切片
- 左闭右开区间内的所有元素
>>> list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[1:2]
[3.4]
>>> list_of_random_things[:2]
[1, 3.4]
>>> list_of_random_things[1:]
[3.4, 'a string', True]
- in or not in
>>> 'this' in 'this is a string'
True
>>> 'in' in 'this is a string'
True
>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True
>>> 5 in [1, 2, 3, 4, 6]
False
- len()
- 列表中的元素数量
- max()
- 列表中的最大元素
- min()
- 列表中的最小元素
- sorted()
- 返回一个排序后的list,且不更改原list
- join()
- 一个字符串操作
- 接受一个字符串列表作为参数,并且返回一个由分隔符连接起来的字符串
>>> new_str = "\n".join(["fore", "aft", "starboard", "port"])
print(new_str)
fore
aft
starboard
port
- append
- 添加一个元素到list的尾部
> letters = ['a', 'b', 'c', 'd']
> letters.append('z')
> print(letters)
['a', 'b', 'c', 'd', 'z']
- 可变性与不可变性
- list是可变得
- 可直接进行=,index改变
- string是不可变的
- 要想改变需要进行创建一个新的字符串来进行更改
- list是可变得
>>> my_lst = [1, 2, 3, 4, 5]
>>> my_lst[0] = 'one'
>>> print(my_lst)
['one', 2, 3, 4, 5]
>>> greeting = "Hello there"
>>> greeting[0] = 'M'
上面可行,下面不可行
Summary
python新的多变量赋值形式
list与其他高级语言不同的地方
在通过索引进行更改的时候,要注意这个对象是可变的么?
通过索引访问的时候,要注意这个对象是有序的么?
- Stirng 和 list 进行更改和赋值的区别
name = "jim"
student = name
name = "john"
# name = 'john' student = 'jim'
#其开辟了两个内存区域存放内容,且name和student各有所指
scores = ["B","A","C"]
grades = scores
scores[1] = "S"
#scores = ["B","S","C"]
#grades = ["B","S","C"]
#其在内存区域当中开辟一个空间来存放一个list,进行赋值操作时所有变量名都指向的是同一个list
Tuples
- Tuple
- 不可变的有序数据结构
- 创建元组时,括号时可选的
- 通常用于存储相关信息
- 用(小括号)声明和创建
#元组解包
dimensions = 52,40,100
length,width,height = dimensions
print("The dimensions are {}*{}*{}".format(length,width,height))
Sets
-
set
- 可修改
- 无序
- 元素唯一
- 用{大括号}声明和创建
-
操作与运算
- in
- 元素是否在set中
- pop
- 随机移除一个元素并返回该元素
- 逻辑运算比其他容器的运算符快
- in
> fruit = {"apple", "banana", "orange", "grapefruit"}
# define a set
> print("watermelon" in fruit)
# check for element
False
> fruit.add("watermelon")
> print(fruit)
# add an element
{'grapefruit', 'orange', 'watermelon', 'banana', 'apple'}
> print(fruit.pop())
grapefruit
# remove a random element
{'orange', 'watermelon', 'banana', 'apple'}
Dictionnaries
- dictionary
- 可变数据类型
- 存储的是键值对
- 键可以是任何不可变的元素
- 键唯一
- 各键不一定相同
> elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
> print(elements["helium"])
# print the value mapped to "helium"
2
> elements["lithium"] = 3
# insert "lithium" with a value of 3 into the dictionary
- in
> print("carbon" in elements)
> print(elements.get("dilithium"))
True
None
- is or is not
> n = elements.get("dilithium")
> print(n is None)
> print(n is not None)
True
False
- Dictionnary的嵌套声明
> elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},
'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}
# todo: Add an 'is_noble_gas' entry to the hydrogen and helium dictionaries
# hint: helium is a noble gas, hydrogen isn't
Summary
["key"]访问若不存在会抛出一个keyerror
get若不存在则返回none
存在的操作有
in,is,is not
新增:
dict["newkey"] = xxx
可变
键值对,键唯一
可通过键访问
键可以是任何不可变的元素