Python基本语法
基础类型
python中的主要基本数据类型是数字(整数和浮点数),布尔值和字符串
字符串操作
字符串可以被
',",'''包裹字符串是python的特殊类型。作为对象,在类中,可以使用
.methodName()表示法调用字符串对象上的方法。字符串类在python中默认可用,因此不需要import语句即可将对象接口用于字符串。
1
2
3firstVariable = 'Hello World'
a = firstVariable.split(' ') # ['Hello', 'World']
' '.join(a) # 'Hello World'拼接字符串
1
2"0" * 3 # '000'
"Fizz" + "Buzz" # 'FizzBuzz'
基础数学
- 有四种不同的数字类型:普通整数,长整数,浮点数和复数。另外,布尔值是普通整数的子类型。
1
2
3
4
5
6
7
8# integer division
130/2 # 65.0
# Exponentiation
2 ** 3 # 8
# Modulo
9 % 3 # 0
操作符
| 比较操作符 | 功能 |
|---|---|
| < | 小于 |
| <= | 小于或等于 |
| > | 大于 |
| >= | 大于或等于 |
| == | 等于 |
| != | 不等于 |
| 逻辑操作符 | 描述 |
|---|---|
| and | 如果两个操作数均为True,则condition变为True. |
| or | 如果两个操作数中的任何一个为True,则condition变为True. |
| not | 用于反转逻辑(不是False变为True,而不是True变为False |
列表
列表后面要加上方括号 [ ] - 切片
1
2
3z = [3, 7, 4, 2]
z[0:2] #[3, 7]
z[:3] # [3, 7, 4]
取列表的最大值, 最小值, 长度, 以及总和
1
print(min(z), max(z), len(z), sum(z)) # 2 7 4 16对列表中对象出现次数进行统计
1
2random_list = [4, 1, 5, 4, 10, 4]
random_list.count(4) # 3返回列表第一个指针
1
2
3random_list.index(4) # 0
random_list.index(4, 3) # 从索引3开始搜索第一个4的位置
random_list.index(4, 5, 6) # random_list.index(value, [start, stop])对列表进行排序
1
2
3
4
5
6
7
8
9x = [3, 7, 2, 11, 8, 10, 4]
y = ['Steve', 'Rachel', 'Michael', 'Adam', 'Monica', 'Jessica', 'Lester']
x.sort() # low to high
x.sort(reverse = True) # high to low
y.sort() # 按字典序排序
new_list = sort(y) # 不改变原列表在列表结尾添加一个对象
1
x.append(3)删除列表中一个对象
1
x.remove(10)删除列表中指定位置的对象
1
2
3
4# Remove item at the index
# this function will also return the item you removed from the list
# Default is the last index
x.pop(3)合并列表 通过在末尾续加的方式来延长列表
1
2x.extend([4, 5])
x + y # 列表里元素类型可以不同在列表指定位置前插入对象
1
x.insert(4, [4, 5]) # [11, 10, 8, 4, [4, 5], 3, 2, 4, 5]
字典
字典是将键(key)映射到值(value)的无序数据结构。值可以是任何值(列表,函数,字符串,任何东西)。键(key)必须是不可变的,例如,数字,字符串或元组。
dict = {'key1': 'value1', 'key2': 'value2'} -
访问字典中的值 1
2
3
4
5webstersDict ={'person': 'a human being, whether an adult or child',
'marathon': 'a running race that is about 26 miles',
'resist': ' to remain strong against the force or effect of (something)',
'run': 'to move with haste; act quickly'}
webstersDict['marathon']
更新字典
1
2
3
4
5
6
7
8
9# add one new key value pair to dictionary
webstersDict['shoe'] = 'an external covering for the human foot'
# update method, update or add more than key value pair at a time
webstersDict.update({'shirt': 'a long- or short-sleeved garment for the upper part of the body', 'shoe': 'an external covering for the human foot, usually of leather and consisting of a more or less stiff or heavy sole and a lighter upper part ending a short distance above, at, or below the ankle.'})
# Removing key from dictionary
del webstersDict['resist']
webstersDict不是所有东西都可以当作Key
使用
get()方法返回给定键的值1
2
3
4storyCount = {'is': 100, 'the': 90, 'Michael': 12, 'runs': 5}
storyCout['run'] # 报错
storyCout.get('run') # None
storyCout.get('run', 0) # 若不存在,则返回默认值0删除键,但同时可以返回值
1
count = storyCount.pop('the')遍历字典
1
2
3
4
5# return keys in dictionary
print(storyCount.keys())
# return values in dictionary
print(storyCount.values())
1 | |
元组
元组是一种序列,就像列表一样。元组和列表之间的区别在于,与列表(可变)不同,元组不能更改(不可变)。
元组使用括号,而列表使用方括号。 - 初始化一个元组 1
2
3
4
5
6
7
8
9
10
11emptyTuple = ()
emptyTuple = tuple()
# 可以通过用逗号分隔值的序列来初始化具有值的元组。
z = (3, 7, 4, 2)
z = 3, 7, 4, 2 # 也可以不要括号
# 要创建仅包含一个值的元组,则需要在项目后面添加一个逗号!
tup1 = ('Michael',)
tup2 = 'Michael',
notTuple = ('Michael') # This is a string, NOT a tuple.
访问元组内的值
1
2z[0]
z[-1] # 负索引切分元组
1
2
3
4
5
6
7# Initialize a tuple
z = (3, 7, 4, 2)
# first index is inclusive (before the :) and last (after the :) is not.
print(z[0:2])
print(z[:3])
print(z[-4:-1])元组是不可改变的,不过可以采用现有元组的一部分来创建新的元组
1
2
3
4
5
6
7
8
9# Initialize tuple
tup1 = ('Python', 'SQL')
# Initialize another Tuple
tup2 = ('R',)
# Create new tuple based on existing tuples
new_tuple = tup1 + tup2;
print(new_tuple)
Tuple 方法
index 方法(索引)
1
2
3
4# Initialize a tuple
animals = ('lama', 'sheep', 'lama', 48)
print(animals.index('lama'))count 方法(计数)
1
print(animals.count('lama'))遍历元组
1
2for item in ('lama', 'sheep', 'lama', 48):
print(item)元组拆包
1
2
3
4# 元组对序列解包非常有用
x, y = (7, 10);
print("Value of x is {}, the value of y is {}.".format(x, y))
# Value of x is 7, the value of y is 10.枚举
1
2
3
4
5# 枚举函数返回一个元组,其中包含每次迭代的计数(从默认为0的开始)和迭代序列获得的值
friends = ('Steve', 'Rachel', 'Michael', 'Monica')
for index, friend in enumerate(friends):
print(index,friend)
元组相对列表的优势
元组比列表更快。如果要定义一组常量值,迭代它,使用元组而不是列表。
元组可以作为字典键,列表不可以用作字典键
1
2
3
4
5bigramsTupleDict = {('this', 'is'): 23,
('is', 'a'): 12,
('a', 'sentence'): 2}
print(bigramsTupleDict)元组可以是集合中的值,列表不可以是集合中的值
### 生成斐波那契序列1
2
3
4
5graphicDesigner = {('this', 'is'),
('is', 'a'),
('a', 'sentence')}
print(graphicDesigner)1
2
3
4
5# 打印出前10个Fibonacci数
a,b = 1,1
for i in range(10):
print("Fib(a): ", a, "b is: ", b)
a,b = b,a+b
for 循环
Task: 从文本中删除标点符号并将最终产品转换为列表:
1
2
3
4
5
6
7
8
9
10
11
12text = '''On a dark desert highway, cool wind in my hair Warm smell of colitas, rising up through the air Up ahead in the distance, I saw a shimmering light My head grew heavy and my sight grew dim I had to stop for the night There she stood in the doorway; I heard the mission bell And I was thinking to myself, "This could be Heaven or this could be Hell" Then she lit up a candle and she showed me the way'''
for char in '-.,;\n"\'':
text = text.replance(char, ' ')
# Split converts string to list.
text.split(' ')[0:20] # 取前20个
cleaned_list = []
for word in text.split(' '):
word_length = len(word)
if word_length > 0:
cleaned_list.append(word)1
2
3
4
5
6
7
8
9# Making empty lists to append even and odd numbers to.
even_numbers = []
odd_numbers = []
for number in range(1,51):
if number % 2 == 0:
even_numbers.append(number)
else:
odd_numbers.append(number)1
2
3def function_name(parameters):
"""docstring"""
statement(s)
返回语句
return语句用于退出函数并返回到调用函数的位置。 1
return [expression_list]1
2
3
4
5
6
7
8
9
10
11
12
13
14def greet(name, msg = "Good morning!"):
"""
This function greets to
the person with the
provided message.
If message is not provided,
it defaults to "Good
morning!"
"""
print("Hello",name + ', ' + msg)
greet("Kate")
greet("Bruce","How do you do?")
关键字参数 在函数调用期间将位置参数与关键字参数混合使用。但必须记住,关键字参数必须遵循位置参数。在关键字参数之后使用位置参数将导致错误。
1
2# greet(msg = "How do you do?", "Bruce")
greet("Bruce",msg = "How do you do?")任意参数 事先并不知道将传递给函数的参数数量。Python允许我们通过具有任意数量参数的函数调用来处理这种情况。这些参数在传递给函数之前被包装到元组中。
### 在列表中移除重复元素1
2
3
4
5
6
7
8
9def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello",name)
greet("Monica","Luke","Steve","John")1
2
3
4
5
6
7
8
9def remove_duplicates(duplicate):
uniques = []
for num in duplicate:
if num not in uniques:
uniques.append(num)
return(uniques)
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]
print(remove_duplicates(duplicate))
Python面向对象编程
面向对象编程(Object-oriented
Programming,简称OOP)是一种编程范例,它提供了一种结构化程序的方法,以便将属性和行为捆绑到单个对象中。
### Python中的类 一个类只提供结构 -
它是应该如何定义某个东西的蓝图,但它实际上并不提供任何真实的内容。可以将"类"视为"某事物的定义",每个事物或对象都是某个类的实例。
### Python对象(实例)
在创建对象的单个实例之前,我们必须首先通过定义类来指定所需的内容。 ###
定义和使用方法 1
2class Dog:
pass
实例属性
所有类都需要创建对象,所有对象都包含称为属性的特征。使用__init __方法通过为对象的初始属性提供其默认值(或状态)来初始化(例如,指定)对象的初始属性。此方法必须至少有一个参数以及自变量,它引用对象本身(例如,Dog)。
1
2
3
4
5class Dog:
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
创建一个新的实例时
__init__会被自动调用。
类属性
1 | |
实例化对象
1 | |
1 | |
实例方法
实例方法在类中定义,用于获取实例的内容。
它们还可用于使用对象的属性执行操作。与__init__方法一样,第一个参数始终是self:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def description(self):
return "{} is {} years old".format(self.name, self.age)
# instance method
def speak(self, sound):
return "{} says {}".format(self.name, sound)
# Instantiate the Dog object
mikey = Dog("Mikey", 6)
# call our instance methods
print(mikey.description())
print(mikey.speak("Gruff Gruff"))
- 修改属性
1
2
3
4
5
6
7
8
9
10
11class Email:
def __init__(self):
self.is_sent = False
def send_email(self):
self.is_sent = True
my_email = Email()
print(my_email.is_sent)
my_email.send_email()
print(my_email.is_sent)
Python对象继承
继承是一个类采用另一个类的属性和方法的过程。新形成的类称为子类,子类派生的类称为父类。
重要的是要注意子类覆盖或扩展父类的功能(例如,属性和行为)。换句话说,子类继承了父项的所有属性和行为,但也可以添加不同行为。最基本的类是一个对象,通常所有其他类都继承为它们的父对象。
定义新类时,Python 3隐式使用object作为父类。所以以下两个定义是等价的:
1
2
3
4
5
6class Dog(object):
pass
# In Python 3, this is the same as:
class Dog:
pass
扩展父类功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18# Child class (inherits from Dog class)
class RussellTerrier(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)
# Child class (inherits from Dog class)
class Bulldog(Dog):
def run(self, speed):
return "{} runs {}".format(self.name, speed)
# Child classes inherit attributes and
# behaviors from the parent class
jim = Bulldog("Jim", 12)
print(jim.description()) # Jim is 12 years old
# Child classes have specific attributes
# and behaviors as well
print(jim.run("slowly")) # Jim runs slowly覆盖父类功能
isinstance()函数用于确定实例是否也是某个父类的实例。1
2
3
4
5
6
7
8
9
10
11
12class Dog:
species = 'mammal'
class SomeBreed(Dog):
pass
class SomeOtherBreed(Dog):
species = 'reptile'
frank = SomeBreed()
print(frank.species) # mammal
beans = SomeOtherBreed()
print(beans.species) # reptile