码迷,mamicode.com
首页 > 编程语言 > 详细

10分钟学会Python

时间:2019-11-14 09:42:24      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:remove   语法   index   rabl   获取   value   class   初学   ges   

#1. 语法

Python中没有强制的语句终止字符,代码块是通过缩进来指示的。缩进表示一个代码块的开始,逆缩进则表示一个代码块的结束。一般用4个空格来表示缩进。

  • 声明以冒号(:)字符结束,并且开启一个缩进级别。
  • 单行注释以井号字符(#)开头,多行注释则以多行字符串的形式出现。
  • 赋值(事实上是将对象绑定到名字)通过等号(“=”)实现
  • 双等号(“==”)用于相等判断
# 本行是注释
some_var = 3
print(some_var)

print(some_var == 4)

if some_var > 1:
    print(‘Python就是这么简单‘)
3
False
Python就是这么简单

  

#2. 导入库

外部库可以使用 import [libname] 关键字来导入,也可以使用 from [libname] import [funcname] 来导入所需要的函数。例如:

import math
math.sqrt(25)
5.0
from math import sqrt
sqrt(25)
5.0

  

#3. 数据类型

查看数据类型:

type(2)
int
type(‘two‘)
str
type(True)
bool

  

类型转换:

float(2)
2.0
int(2.9)
2
str(2.9)
‘2.9‘

  

#4. 数学运算

10 + 4
14
10 - 4
6
10 * 4
40
10 % 4      # 计算余数
2
10 / 4
2.5

  

#5. 比较和布尔运算

赋值

x = 5

比较:

x > 3
True
x >= 3
True
x != 3
True
x == 5
True

  

布尔运算:

# and:与
5 > 3 and 6 > 3
True
# or:或
5 > 3 or 5 < 3
True
# not:非
not False
True

  

#6. 条件表达式

# if 语句
if x > 0:
    print(‘positive‘)
positive
# if/else 语句
if x > 0:
    print(‘positive‘)
else:
    print(‘zero or negative‘)
positive
# if/elif/else 语句
if x > 0:
    print(‘positive‘)
elif x == 0:
    print(‘zero‘)
else:
    print(‘negative‘)
positive

  

#7. 列表

  • 列表的特点: 有序,可迭代,可变,可以包含多个数据类型

创建列表

# 两种创建空列表的方法如下
empty_list = []
empty_list = list()
# 创建列表
simpsons = [‘homer‘, ‘marge‘, ‘bart‘]

  

获取列表数据:

# 列表的第0个元素(列表的下标从0开始,这和C语言等一致)
simpsons[0]
‘homer‘
# 列表元素个数
len(simpsons)
3

  

列表方法:

# 在尾部追加,操作符+=完成同样的功能
simpsons.append(‘lisa‘)
simpsons
[‘homer‘, ‘marge‘, ‘bart‘, ‘lisa‘]
# 在尾部追加多个元素
simpsons.extend([‘itchy‘, ‘scratchy‘])
simpsons
[‘homer‘, ‘marge‘, ‘bart‘, ‘lisa‘, ‘itchy‘, ‘scratchy‘] # 在索引位置处将数据项插入列表 simpsons.insert(0, ‘maggie‘) simpsons
[‘maggie‘, ‘homer‘, ‘marge‘, ‘bart‘, ‘lisa‘, ‘itchy‘, ‘scratchy‘] # 列表从左往右搜索第一个出现的元素,并移除 simpsons.remove(‘bart‘) simpsons
[‘maggie‘, ‘homer‘, ‘marge‘, ‘lisa‘, ‘itchy‘, ‘scratchy‘] # 替代列表第一个元素 simpsons[0] = ‘krusty‘ simpsons
[‘krusty‘, ‘homer‘, ‘marge‘, ‘lisa‘, ‘itchy‘, ‘scratchy‘] # 统计元素出现次数 simpsons.count(‘lisa‘) 1 # returns index of first instance simpsons.index(‘itchy‘) 4

  

列表切片:

weekdays = [‘mon‘, ‘tues‘, ‘wed‘, ‘thurs‘, ‘fri‘]
# 第一个元素,索引值为0
weekdays[0]
‘mon‘
# 前三个元素,索引值为0、1、2,,其中0可以省略
print(weekdays[0:3] == weekdays[:3])
weekdays[0:3]
True
[‘mon‘, ‘tues‘, ‘wed‘]
# 从索引值为3的元素的位置到最后位置的元素
weekdays[3:]
[‘thurs‘, ‘fri‘]
# 最后一个元素
weekdays[-1]
‘fri‘
# 每隔两个元素进行存取
weekdays[::2]
[‘mon‘, ‘wed‘, ‘fri‘]
# 反转列表,等价于list(reversed(weekdays))
weekdays[::-1]
[‘fri‘, ‘thurs‘, ‘wed‘, ‘tues‘, ‘mon‘]
# 对列表进行排序 (原地修改列表但不返回列表)
simpsons.sort()
simpsons
[‘homer‘, ‘itchy‘, ‘krusty‘, ‘lisa‘, ‘marge‘, ‘scratchy‘]
# 反向排序
simpsons.sort(reverse=True)
simpsons
[‘scratchy‘, ‘marge‘, ‘lisa‘, ‘krusty‘, ‘itchy‘, ‘homer‘]
# 根据传入的规则排序,以长度为例
simpsons.sort(key=len)
simpsons
[‘lisa‘, ‘marge‘, ‘itchy‘, ‘homer‘, ‘krusty‘, ‘scratchy‘]
# 返回已排序列表(并不修改原列表),可以传入排序规则:
simpsons = [ ‘krusty‘, ‘itchy‘, ‘scratchy‘, ‘lisa‘]
sorted(simpsons, key=len)
[‘lisa‘, ‘itchy‘, ‘krusty‘, ‘scratchy‘]
# 对象引用
num = [10,20,30,40,50]
same_num = num
# 会同时修改两个对象
same_num[0] = 0
print(num)
print(same_num)
[0, 20, 30, 40, 50]
[0, 20, 30, 40, 50]
# 检查是否是同一个对象
num is same_num
True
# 判断两个对象是否相等
num == same_num
True

  

#8. 元组

  • 元组性质: 有序,可迭代,不可变,可以包含多个数据类型
  • 类似于列表, 但不可变
# 直接创建一个元组
digits = (0, 1, ‘two‘)
# 将列表转化为元组
digits = tuple([0, 1, ‘two‘])
# 元组第三个位置的元素
digits[2]
‘two‘
# 元组长度
len(digits)
3
# 统计元组中元素出现的次数
digits.count(‘two‘)
1
# 返回该元素第一次出现的索引值
digits.index(1)
1
# 元组不可修改,下面语句会报错
# digits[2] = 2

  

#9. 字符串

  • 字符串性质: 可迭代,不可变
# 创建字符串
s = ‘I like you‘
# 字符串切片
s[0]
‘I‘
# 长度
len(s)
10

  

字符串切片类似于列表切片:

s[:6]
‘I like‘
s[7:]
‘you‘
s[-1]
‘u‘

  

字符串方法 (并不修改原字符串):

s.lower()
‘i like you‘
s.upper()
‘I LIKE YOU‘
s.startswith(‘I‘)
True
s.endswith(‘you‘)
True
# 返回在字符串中的最左位置,如果没有找到,就返回-1
s.find(‘like‘)
2
# 字符串替换
s.replace(‘like‘, ‘love‘)
‘I love you‘

  

字符串分割:

# 返回一个被空白字符分割的字符串列表
s.split(‘ ‘)
[‘I‘, ‘like‘, ‘you‘]
# 返回一个被特定字符分割的字符串列表
s2 = ‘a, an, the‘
s2.split(‘,‘)
[‘a‘, ‘ an‘, ‘ the‘]
# 字符串拼接
stooges = [‘larry‘, ‘curly‘, ‘moe‘]
‘ ‘.join(stooges)
‘larry curly moe‘
# + 也可作字符串拼接
s3 = ‘The meaning of life is‘
s4 = ‘42‘
s3 + ‘ ‘ + s4
‘The meaning of life is 42‘
# 移除开始和结尾的空白字符
s5 = ‘  ham and cheese  ‘
s5.strip()
‘ham and cheese‘

  

格式化字符串:

# 方法1
‘raining %s and %s‘ % (‘cats‘, ‘dogs‘)
‘raining cats and dogs‘
# 方法2
‘raining {} and {}‘.format(‘cats‘, ‘dogs‘)
‘raining cats and dogs‘

  

#10. 字典

  • 字典性质: 无序,可迭代,可变,可以包含多个数据类型
  • 由键-值对组成
  • 键必须是唯一的, 可以是字符串、数字、元组
  • 值可以是任何类型

字典的键与值:

# 创建一个空字典(两种方法)
empty_dict = {}
empty_dict = dict()
# 创建字典(两种方法)
family = {‘dad‘:‘homer‘, ‘mom‘:‘marge‘, ‘size‘:6}
family = dict(dad=‘homer‘, mom=‘marge‘, size=6)
family
{‘dad‘: ‘homer‘, ‘mom‘: ‘marge‘, ‘size‘: 6}
# 传入键名,获取字典键值
family[‘dad‘]
‘homer‘
# 返回字典的键-值对数目
len(family)
3
# 检查字典中是否含有某个键名
‘mom‘ in family
True
# 返回键名
family.keys()
dict_keys([‘size‘, ‘dad‘, ‘mom‘])
# 返回键值
family.values()
dict_values([6, ‘homer‘, ‘marge‘])
# 返回键值对
family.items()
dict_items([(‘size‘, 6), (‘dad‘, ‘homer‘), (‘mom‘, ‘marge‘)])

  

修改字典:

# 增加一个键-值
family[‘cat‘] = ‘snowball‘
family
{‘cat‘: ‘snowball‘, ‘dad‘: ‘homer‘, ‘mom‘: ‘marge‘, ‘size‘: 6}
# 编辑一个已存在的键-值
family[‘cat‘] = ‘snowball ii‘
family
{‘cat‘: ‘snowball ii‘, ‘dad‘: ‘homer‘, ‘mom‘: ‘marge‘, ‘size‘: 6}
# 删除一个键-值
del family[‘cat‘]
family
{‘dad‘: ‘homer‘, ‘mom‘: ‘marge‘, ‘size‘: 6}
# 字典值可以是列表
family[‘kids‘] = [‘bart‘, ‘lisa‘]
family
{‘dad‘: ‘homer‘, ‘kids‘: [‘bart‘, ‘lisa‘], ‘mom‘: ‘marge‘, ‘size‘: 6}
# 增加多个键-值
family.update({‘baby‘:‘maggie‘, ‘grandpa‘:‘abe‘})
family
{‘baby‘: ‘maggie‘,
 ‘dad‘: ‘homer‘,
 ‘grandpa‘: ‘abe‘,
 ‘kids‘: [‘bart‘, ‘lisa‘],
 ‘mom‘: ‘marge‘,
 ‘size‘: 6}

  

获取键值的一个更安全的方法(get):

# 获取字典值,等价于family[‘mom‘]
family.get(‘mom‘)
‘marge‘
# 如果字典中不存在,返回一个默认值
family.get(‘grandma‘, ‘not found‘)
‘not found‘

  

#11. 集合

  • 集合性质: 无序, 可迭代, 可变, 可以包含多个数据类型
  • 集合中元素是唯一的(字符串, 数字, or 元组)
  • 类似于字典,只有键名,没有键值

创建集合:

# 创建空集合
empty_set = set()
# 创建集合
languages = {‘python‘, ‘r‘, ‘java‘}
# 将列表转化为集合
snakes = set([‘cobra‘, ‘viper‘, ‘python‘])

  

集合运算:

# 交集
languages & snakes
{‘python‘}
# 并集
languages | snakes
{‘cobra‘, ‘java‘, ‘python‘, ‘r‘, ‘viper‘}
# 差集
languages - snakes
{‘java‘, ‘r‘}

  

修改集合 (并不返回集合):

# a增加元素
languages.add(‘sql‘)
languages
{‘java‘, ‘python‘, ‘r‘, ‘sql‘}
# 增加一个已存在的元素
languages.add(‘r‘)
languages
{‘java‘, ‘python‘, ‘r‘, ‘sql‘}
# 移除元素
languages.remove(‘java‘)
languages
{‘python‘, ‘r‘, ‘sql‘}
# 移除所有元素
languages.clear()
languages
set()

  

从列表中获取唯一元素的排序列表:

sorted(set([9, 0, 2, 1, 0]))
[0, 1, 2, 9]

  

#12. 函数

定义没有参数、没有返回值的函数:

def print_text():
    print(‘this is text‘)
# 调用函数
print_text()
this is text

  

定义含有一个参数、含有一个返回值的函数:

# 定义函数
def square_this(x):
    return x**2
# 调用函数
result = square_this(3)
print(result)
9

  

定义含有两个位置参数(非默认值)、一个关键字参数(默认值)的函数:

def calc(a, b, op=‘add‘):
    if op == ‘add‘:
        return a + b
    elif op == ‘sub‘:
        return a - b
    else:
        print(‘valid operations are add and sub‘)
# 调用函数
calc(10, 4, op=‘add‘)
14
# 通过参数位置来传入参数值
calc(10, 4, ‘add‘)
14
# ‘op’关键字参数为默认值
calc(10, 4)
14
calc(10, 4, ‘sub‘)
6
calc(10, 4, ‘div‘)
valid operations are add and sub

  

如果您尚未编写函数体,请使用pass作为占位符:

def stub():
    pass

  

函数含有两个返回值:

def min_max(nums):
    return min(nums), max(nums)
# 多个返回值可以绑定到类型为元组的变量上
nums = [1, 2, 3]
min_max_num = min_max(nums)
min_max_num
(1, 3)
# 多个返回值绑定到多个变量上()通过元组解包的方式
min_num, max_num = min_max(nums)
print(min_num)
print(max_num)
1
3

  

#13. 匿名(Lambda)函数

  • 主要用于临时定义由另一个函数使用的函数

定义函数:

# 最常见的定义函数的方法——def
def squared(x):
    return x**2
# 使用lambda定义函数的方法,等价于def函数定义
squared = lambda x: x**2

  

依据字符串最后一个元素的顺序,将字符串列表进行排序:

# 使用def函数定义的方法
simpsons = [‘homer‘, ‘marge‘, ‘bart‘]
def last_letter(word):
    return word[-1]
sorted(simpsons, key=last_letter)
[‘marge‘, ‘homer‘, ‘bart‘]
# 使用lambda函数定义的方法
sorted(simpsons, key=lambda word: word[-1])
[‘marge‘, ‘homer‘, ‘bart‘]

  

#14. For循环与While循环

for 循环:

# for循环
fruits = [‘apple‘, ‘orange‘]
for fruit in fruits:
    print(fruit.upper())
APPLE
ORANGE
# 对字典的循环,依次打印字典的键名和键值
family = {‘dad‘:‘homer‘, ‘mom‘:‘marge‘, ‘size‘:6}
for key, value in family.items():
    print(key, value)
size 6
dad homer
mom marge
# 对列表的循环,依次打印列表元素的索引值和元素
for index, fruit in enumerate(fruits):
    print(index, fruit)
0 apple
1 orange

  

while 循环:

count = 0
while count < 5:
    print(‘This will print 5 times‘)
    count += 1    # 等价于 ‘count = count + 1‘
This will print 5 times
This will print 5 times
This will print 5 times
This will print 5 times
This will print 5 times

  

#15. 生成式

列表生成式:

# 通过for循环获得一个列表,该列表的每个元素是原始列表对应元素的三次方
nums = [1, 2, 3, 4, 5]
cubes = []
for num in nums:
    cubes.append(num**3)
cubes
[1, 8, 27, 64, 125]
# 使用列表生成式
cubes = [num**3 for num in nums]
cubes
[1, 8, 27, 64, 125]
# 如果只想获得偶数值的列表
# 语法: [expression for variable in iterable if condition]
cubes_of_even = [num**3 for num in nums if num % 2 == 0]
cubes_of_even
[8, 64]

  

集合生成式:

fruits = [‘apple‘, ‘banana‘, ‘cherry‘]
unique_lengths = {len(fruit) for fruit in fruits}
unique_lengths
{5, 6}

  

字典生成式:

fruit_lengths = {fruit:len(fruit) for fruit in fruits}
fruit_lengths
{‘apple‘: 5, ‘banana‘: 6, ‘cherry‘: 6}
fruit_indices = {fruit:index for index, fruit in enumerate(fruits)}
fruit_indices
{‘apple‘: 0, ‘banana‘: 1, ‘cherry‘: 2}

  

#16. FAQ

1. 应该学Python 2 还是 Python 3?

如果你还在问这个问题,选择Python 3。Python 3已经被广泛支持和使用,Python 2的程序可以通过 2to3 转换为Python 3。对初学者来说,Python 2和3区别不大。BigQuant的策略开发语言是Python 3。

10分钟学会Python

标签:remove   语法   index   rabl   获取   value   class   初学   ges   

原文地址:https://www.cnblogs.com/chamge/p/11854632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!