python随记

python随记:

方法:

方法描述实例
print()打印输出print(“Hello, World!”)
定义变量变量规则message = “Hello, World!”
字符串被引号修饰的字符字符串定义例子
“zhao yun”.title()字符串首字母大写结果为:Zhao Yun
“zhao yun”.upper()字符串全部大写结果为:ZHAO YUN
“ZHAO YUN”.lower()字符串全部小写结果为:zhao yun
“zhao” + ” ” + “yun”字符串拼接结果为:zhao yun
’ python ‘.lstrip()删左空白结果为:’python ‘
’ python ‘.rstrip()删右空白结果为:’ python’
’ python ‘.strip()删两端空白结果为:’python’
3/2除法会保留小数(python2不会)结果为:1.5
3 ** 2乘方运算结果为:9
0.2 + 0.1浮点数相加特殊例子
“A” + str(18) + “B”数字字符串拼接结果为:A 18rd B<错误情况>
#python注释从#号开始到本行结束为注释内容
[‘A’, ‘B’, ‘C’]列表:按特定顺序排列的元素列表概念
对相应位置的元素赋值修改列表元素修改示例
append(“A”) insert(index, ‘B’)添加列表元素添加示例
del 列表名[index]删除列表元素del方法删除示例
pop(默认/index)删除列表元素pop方法删除示例
remove(“A”)删除列表元素remove方法删除示例
A.sort()
A.sort(reverse=True)
对列表永久排序(原地操作)永久排序示例
sorted()
sorted(A, reverse=True)
不修改原列表,对列表进行临时排序临时排序示例
A.reverse()反向打印原有列表临打印示例
len(A)获取列表长度获取列表长度示例
range()生成数字列表生成数列示例
min(A) max(A) sum(A)数字列表最大值、最小值、元素之和数字列表统计计算示例
print(list(range(1, 6, 2)))将数据转换成列表结果为:[1, 3, 5]
for循环对列表进行遍历for循环示例
A[起始:结束:步长]切片操作切片示例
深、浅复制列表复制列表复制示例
my_tuple = (1,)元组(tuple)元组示例
  1. 变量名只能包含字母、数字和下划线,且不能以数字开头。
  2. 变量名不能包含空格,一般用下划线分隔变量中的单词,也可以用驼峰命名法,但Python提倡用下划线。
  3. Python中的关键字和自带函数不能用于变量名。
  4. 变量名应该简短明了。
  5. 慎用小写字母 l 和大写字母O,因为这两个字母容易被看成数字1和0。
  6. Python解释器不对代码进行拼写检查,应尽量避免命名错误,比如变量名中少写个字母之类的,否则会出现NameError。

字符串定义示例:

三引号主要用于字符串是多行的情况,同时它也常用于注释

注意,若字符串中出现了和最外层引号相同的引号时,会出现SyntaxError

  • “This is a string.”
  • ‘This is also a string.’
  • ‘I told my friend, “Python is my favorite language!”’
  • “The language ‘Python’ is named after Monty Python, not the snake.”
  • “One of Python’s strengths is its diverse and supportive community.”
  • “”“
    this is line 1;
    this is line 2.
    “”“
  • ”’
    this is line 1;
    this is line 2.
    ”’

浮点数计算结果可能包含多位:

>>> 0.1 + 0.1
0.2
>>> 0.2 + 0.1  #和计算机内部数字的表示方法有关
0.30000000000000004
>>> 3 * 0.1
0.30000000000000004

浮点数计算结果可能包含多位:

# 代码:
age = 18
message = "Happy " + age + "rd Birthday!"

# 结果:
Traceback (most recent call last):
  File "E:/Code/Python/Study/day1/chapter1.py", line 38, in <module>
message = "Happy " + age + "rd Birthday!"
TypeError: must be str, not int

列表:

  • 列表中的元素可以是不同类型。
  • 用中括号[]来表示列表,并用逗号分隔其中的元素。
  • 索引从0开始,而不是从1开始。
  • 支持索引为负数,表示从后往前数,“-1”表示倒数第1个元素。
  • 不管索引是正数还是负数,都要注意索引越界问题。

修改元素:

# 代码:
# 修改第一个元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

motorcycles[0] = "ducati"
print(motorcycles)

# 结果:
['honda', 'yamaha', 'suzuki']
['ducati', 'yamaha', 'suzuki']

添加元素:

# 代码:
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

# 在列表末尾添加元素
motorcycles.append("ducati")
# 在列表任意位置添加元素
motorcycles.insert(0, 'ducati')
print(motorcycles)

# 结果:
['honda', 'yamaha', 'suzuki']
['ducati', 'honda', 'yamaha', 'suzuki', 'ducati']

# 动态建立列表:
motorcycles = []  # 此句很重要!表示声明一个列表!
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)

# 结果:
['honda', 'yamaha', 'suzuki']

删除元素:

使用del删除元素:

# 代码:
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
# del 可删除任意位置的列表元素,前提是知道其索引
del motorcycles[0]
print(motorcycles)

# 结果:
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']

使用pop删除元素:

  • 对删除的元素,有后续操作时使用该方法
  • 方法中不带参数时,默认删除最后一个元素
  • 方法中带参数时,删除指定位置的元素(注意越界问题)
# 代码:
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)

last_owned = motorcycles.pop()  # 默认
print("The last motorcycle I owned was a " + last_owned.title() + ".")
print(motorcycles)

motorcycles.pop(1)  # 传入参数
print(motorcycles)

# 结果:
['honda', 'yamaha', 'suzuki']
The last motorcycle I owned was a Suzuki.
['honda', 'yamaha']
['honda']

使用remove删除元素:

  • 使用情景:当不知道元素索引,但知道元素值时
  • 如果列表中有多个相同的值,romve() 方法只删除第一个
# 代码:
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)

motorcycles.remove('ducati')
print(motorcycles)

# 结果:
['honda', 'yamaha', 'suzuki', 'ducati']
['honda', 'yamaha', 'suzuki']

永久排序:

  • 按ASCII码进行的排序
  • 反向排序,只需要传入关键字参数reverse=True
# 代码:
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

# 结果:
['audi', 'bmw', 'subaru', 'toyota']

临时排序:

  • 按ASCII码进行的排序
  • 反向排序,只需要传入关键字参数reverse=True
# 代码:
cars = ['bmw', 'audi', 'toyota', 'subaru']

print("Here is the original list:")
print(cars)

print("\nHere is ths sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars)

# 结果:
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']

Here is ths sorted list:
['audi', 'bmw', 'subaru', 'toyota']

Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']

反向打印列表:

# 代码:
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)

cars.reverse()  # 注意!并没有排序后再反向!
print(cars)

# 结果:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']

确定列表长度:

# 代码:
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))

# 结果:
4

确定列表长度:

  • 用于标识循环次数,或者用于生成更复杂的列表
# 代码:
print(list(range(6)))         # 结束值(不包含结束值)
print(list(range(1, 6)))      # 起始值(包含),结束值(不含)
print(list(range(1, 6, 2)))   # 起始值,结束值,步长;最后一个数小于结束值
print(list(range(6, 1, -1)))  # 负数步长,此时起始值要大于结束值
print(list(range(1, 6, -1)))  # 负数步长,若起始值小于结束值,则输出空列表

# 结果:
[0, 1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 3, 5]
[6, 5, 4, 3, 2]
[]

for循环:

  • for关键字所在的行最后有一个冒号。
  • Python中的代码块都是以缩进为标准,IndentationError指缩进错误。
# 代码:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician.title() + ", that was a great trick")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")

print("Thank you, everyone. That was a great magic show!")

# 输出:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.

David, that was a great trick!
I can't wait to see your next trick, David.

Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you, everyone. That was a great magic show!


# 用for循环range()生成的列表:
squares = []
for value in range(1, 11):
    squares.append(value ** 2 + 1)
print(squares)

# 结果:
[2, 5, 10, 17, 26, 37, 50, 65, 82, 101]


# 列表解析法:
squares = [value ** 2 for value in range(1, 11)]
print(squares)

squares_2 = [value ** 2 for value in range(1, 11) if value % 2 == 0]
print(squares_2)
# 结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[4, 16, 36, 64, 100]

对数字列表执行简单的统计计算:

# 代码:
digits = list(range(10))
print(min(digits), max(digits), sum(digits))

# 结果:
0 9 45

切片操作:

  • 起始,结束,步长都可以为负值。
  • 如果步长为正数,则起始位置要在结束位置的左边;若步长为负数,则起始位置要在结束位置的右边。
# 代码:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
# [起始:结束:步长], 其中,结果列表包含起始索引,但不包含结束索引
print(players[0:3])
print(players[:3])   # 如果从0开始切片,0可以省略
print(players[1:3])
print(players[2:])   # 如果要便利到最后一个元素,结束索引可以省略,此时最后一个元素会被包含
print(players[-3:])  
print(players[::2])  # 设置了步长,但省略了结束索引,列表最后一个元素如果被遍历到,则会被包含
print(players[:4:2]) # 设置了步长和结束索引,索引4的元素也被遍历到了,但不会被包含在结果中

# 结果:
['charles', 'martina', 'michael']
['charles', 'martina', 'michael']
['martina', 'michael']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']
['charles', 'michael', 'eli']
['charles', 'michael']

复制列表:

  • 有深浅复制的问题。
  • 浅复制:如果直接将一个变量赋值到另一个变量,那么内存中的数据依然只有一份,而不是两份,这两个变量都指向内存中同一个存放数据的内存区域。
  • 深复制:在内存中将原来的数据复制出一份新的数据,切片操作则是实现深复制的一种方法。
# 代码:
# 浅复制
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players)

names = players
names.append("test")
print(players)

# 结果:
['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'test']

# 代码:
# 深复制
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players)

names = players[:]
names.append("test")
print(names)
print(players)

# 结果:
['charles', 'martina', 'michael', 'florence', 'eli']
['charles', 'martina', 'michael', 'florence', 'eli', 'test']
['charles', 'martina', 'michael', 'florence', 'eli']

元组(tuple):

  • 使用情景:创建一系列不可修改的元素
  • 元组用圆括号来标识。
  • 对元组中元素的访问以及对元组的遍历都和对列表的操作一样。
  • 元组中的元素不能被改变。 虽然元组中的元素不能改变,但是元组变量的值可以改变。
# 代码:
my_tuple = ()    # 空元组
one_tuple = (1,) # 声明含有一个元素的元组。不是one_tuple = (1)
test_tuple = (1, 2, 3, 4, 5)
print(test_tuple)
test_tuple = (2, 3, 4, 5, 6)
print(test_tuple)

# 结果:
(1, 2, 3, 4, 5)
(2, 3, 4, 5, 6)

错误:

1、Python保存时提示“SyntaxError: Non-ASCII character ‘\xe8’ in file”
在文件头部加上: -*- coding: utf-8 -*-

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值