标签:remove 语法 index rabl 获取 value class 初学 ges
Python中没有强制的语句终止字符,代码块是通过缩进来指示的。缩进表示一个代码块的开始,逆缩进则表示一个代码块的结束。一般用4个空格来表示缩进。
# 本行是注释
some_var = 3
print(some_var)
print(some_var == 4)
if some_var > 1:
print(‘Python就是这么简单‘)
3
False
Python就是这么简单
外部库可以使用 import [libname] 关键字来导入,也可以使用 from [libname] import [funcname] 来导入所需要的函数。例如:
import math math.sqrt(25) 5.0 from math import sqrt sqrt(25) 5.0
查看数据类型:
type(2) int type(‘two‘) str type(True) bool
类型转换:
float(2) 2.0 int(2.9) 2 str(2.9) ‘2.9‘
10 + 4 14 10 - 4 6 10 * 4 40 10 % 4 # 计算余数 2 10 / 4 2.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
# 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
创建列表
# 两种创建空列表的方法如下 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
# 直接创建一个元组 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
# 创建字符串 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‘
字典的键与值:
# 创建一个空字典(两种方法)
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‘
创建集合:
# 创建空集合
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]
定义没有参数、没有返回值的函数:
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
定义函数:
# 最常见的定义函数的方法——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‘]
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
列表生成式:
# 通过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}
1. 应该学Python 2 还是 Python 3?
如果你还在问这个问题,选择Python 3。Python 3已经被广泛支持和使用,Python 2的程序可以通过 2to3 转换为Python 3。对初学者来说,Python 2和3区别不大。BigQuant的策略开发语言是Python 3。
标签:remove 语法 index rabl 获取 value class 初学 ges
原文地址:https://www.cnblogs.com/chamge/p/11854632.html