python学习笔记

1.变量名称区分大小写(age、Age 和 AGE 是三个不同的变量)
2.在函数内部创建一个与全局变量同名的变量:

x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)
函数内部重新定义变量,不影响外部变量

用了 global 关键字,则该变量属于全局范围:
x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)


type() 函数获取任何对象的数据类型
4.使用三个(单/双)引号将多行字符串赋值给变量:

a = '''Python is a widely used general-purpose, high level programming language.
It was initially designed by Guido van Rossum in 1991
and developed by Python Software Foundation.
It was mainly developed for emphasis on code readability,
and its syntax allows programmers to express concepts in fewer lines of code.'''
5.Python 没有字符数据类型,单个字符就是长度为 1 的字符串。

方括号可用于访问字符串的元素。

a = "Hello, World!"
print(a[1])
获取从位置 2 到位置 5(不包括)的字符:
b = "Hello, World!"
print(b[2:5])
6.字符串方法:
strip() 方法删除开头和结尾的空白字符
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

lower() 返回小写的字符串,upper() 方法返回大写的字符串

a = "Hello, World!"
print(a.replace("World", "Kitty"))

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

7.检查字符串
检查字符串中是否存在特定短语或字符,我们可以使用 in 或 not in 关键字。

txt = "China is a great country"
x = "ina" in txt
print(x)

8.format将元素放入字符串中间
format() 方法接受传递的参数,格式化它们,并将它们放在占位符 {} 所在的字符串中

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

放到指定位置:

myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

占位符
可以使用命名索引 {price}、编号索引{0}、甚至空的占位符 {} 来标识占位符

txt1 = "My name is {fname}, I'am {age}".format(fname = "Bill", age = 64)
txt2 = "My name is {0}, I'am {1}".format("Bill",64)
txt3 = "My name is {}, I'am {}".format("Bill",64)

9.bool
除空字符串外,任何字符串均为 True。

除 0 外,任何数字均为 True。

除空列表外,任何列表、元组、集合和字典均为 True。

false的:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

10.运算符
| ** | 幂 | x ** y |
| // | 地板除(取整除) | x // y |
^ 异或
x > 3 and x < 10,x > 3 or x < 4,not(x > 3 and x < 10)
Python 身份运算符
| 如果两个变量是同一个对象,则返回 true。 | x is y |
| 如果两个变量不是同一个对象,则返回 true。 | x is not y |
看是否它们实际上是同一个对象,则具有相同的内存位置

in

x = ["apple", "banana"]

print("banana" in x)

11.集合(数组)

[] 列表(List)是一种有序和可更改的集合。允许重复的成员。
在指定的索引处添加项目,请使用 insert() 方法

thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange") #第二个位置
remove() 方法删除指定的项目:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
pop() 方法删除指定的索引(如果未指定索引,则删除最后一项)()里面是数字
thislist.pop(1)
del 关键字删除指定的索引或整个列表:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
del thislist
clear() 方法清空列表:
thislist.clear()

复制列表
(1)list2 = list1,list2 将只是对 list1 的引用,list1 中所做的更改也将自动在 list2 中进行。
(2)mylist = thislist.copy()
(3)mylist = list(thislist)
2和3都是新建列表进行复制

合并两个列表
(1)+:list3 = list1 + list2
(2)for x in list2:
list1.append(x)
(3) extend() :list1.extend(list2)

列表的内建方法:

append() 在列表的末尾添加一个元素
clear() 删除列表中的所有元素
copy() 返回列表的副本
count() 返回具有指定值的元素数量。
extend() 将列表元素(或任何可迭代的元素)添加到当前列表的末尾
index() 返回具有指定值的第一个元素的索引(下标)
insert() 在指定位置添加元素
pop() 删除指定位置的元素
remove() 删除具有指定值的项目
reverse() 颠倒列表的顺序
sort() 对列表进行排序 (默认升序)
sort:
reverse 可选。reverse=True 将对列表进行降序排序。默认是 reverse=False。
key 可选。指定表明了排序标准的函数。
按照值的长度对列表进行排序:

返回值的长度的函数:

def myFunc(e):
return len(e)

cars = ['Porsche', 'Audi', 'BMW', 'Volvo']

cars.sort(key=myFunc)

() 元组(Tuple)是一种有序且不可更改的集合。允许重复的成员。
把元组转换为列表即可进行更改:

x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

创建仅包含一个项目的元组,您必须在该项目后添加一个逗号,否则 Python 无法将变量识别为元组,而是字符串。
thistuple = ("apple",)

del thistuple 删除元组
tuple3 = tuple1 + tuple2 合并元组
元组的内建方法:
| count() | 返回元组中指定值出现的次数。 |
| index() | 在元组中搜索指定的值并返回它被找到的位置。 |

{} 集合(Set)是一个无序和无索引的集合。没有重复的成员。
for 和 in都可以用,但是无法通过下标索引
集合一旦创建,就无法更改项目,但是可以添加新项目:
(1)thisset.add("orange")
(2)update() 方法将多个项添加到集合中:thisset.update(["orange", "mango", "grapes"])
删除:thisset.remove("banana") 或者 thisset.discard("banana")
remove 的元素如果不存在,则引发错误,discard不会
.clear清空 del thisset 彻底删除集合
集合的合并(都会排除重复项):
(1)union :set3 = set1.union(set2)
(2)update:set1.update(set2)
set的内建方法:

add() 向集合添加元素。
clear() 删除集合中的所有元素。
copy() 返回集合的副本。
difference() 返回包含两个或更多集合之间差异的集合。
difference_update() 删除两个集合中都存在的项目
discard() 删除指定项目。
intersection() 返回为两个其他集合的交集的集合。
intersection_update() 删除此集合中不存在于其他指定集合中的项目。
isdisjoint() 返回两个集合是否有交集。
issubset() 返回另一个集合是否包含此集合。
issuperset() 返回此集合是否包含另一个集合。
pop() 从集合中删除一个元素。
remove() 删除指定元素。
symmetric_difference() 返回具有两组集合的对称差集的集合。
symmetric_difference_update() 插入此集合和另一个集合的对称差集。
union() 返回包含集合并集的集合。
update() 用此集合和其他集合的并集来更新集合

{} 词典(Dictionary)是一个无序,可变和有索引的集合。没有重复的成员,用花括号编写,拥有键和值。

thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
用键名来访问值,获取 "model" 键的值:
x = thisdict["model"]
等同于get方法:x = thisdict.get("model")

values() 函数返回字典的值:thisdict.values()

for x in thisdict.values():

items() 函数遍历键和值:thisdict.items()

for x, y in thisdict.items():

字典的in关键字,只能检查是否存在指定的键:

if "model" in thisdict:

添加项目:使用新的索引键并为其赋值

thisdict["color"] = "red"

删除:
(1)pop:删除指定键名的项
thisdict.pop("model")
(2)popitem() :删除最后插入的项目
(3)del:del thisdict["model"]
del thisdict
(4)clear():thisdict.clear()清空字典

和列表一样,不能用=来复制字典:
(1)copy方法:mydict = thisdict.copy()
(2)dict方法:mydict = dict(thisdict)

dict构造字典:

thisdict = dict(brand="Porsche", model="911", year=1963)
# 请注意,关键字不是字符串字面量
# 请注意,使用了等号而不是冒号来赋值

if:

if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

简写 If:
if a > b: print("a is greater than b")
简写 If ... Else:
print("A") if a > b else print("B")
print("A") if a > b else print("=") if a == b else print("B")

组合条件语句(and or)
if a > b and c > a:

if 语句不能为空,为空要写pass

while语句:
break/continue:

i = 1
while i < 7:
  print(i)
  if i == 3:
    break
  i += 1

接else:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

for:python的for是迭代的思想,用于迭代序列(即列表,元组,字典,集合或字符串)
循环遍历单词 "banana" 中的字母:


for x in "banana":
  print(x)

12.函数

def my_function(fname):
  print(fname + " Gates")

my_function("Bill")

默认参数值的函数:

def my_function(country = "China"):
  print("I am from " + country)

my_function("Sweden")
my_function()  # 调用了不带参数的函数,则使用默认值

需要返回值,用return

多个关键字作为参数,key=value:

def my_function(child3, child2, child1):
  print("The youngest child is " + child3)

my_function(child1 = "Phoebe", child2 = "Jennifer", child3 = "Rory")

参数数量未知,参数名前加*:

def my_function(*kids):
  print("The youngest child is " + kids[2])

my_function("Phoebe", "Jennifer", "Rory")

13.类/对象
和Java一样都是面向对象的语言,有类
创建类:使用名为 x 的属性,创建一个名为 MyClass 的类:

class MyClass:
  x = 5

创建对象:
使用名为 myClass 的类来创建对象:

p1 = MyClass()
print(p1.x)

实例:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("Bill", 63)

对象方法:对象也可以包含方法。对象中的方法是属于该对象的函数。
在 Person 类中创建方法:插入函数,并在 p1 对象上执行它:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("Bill", 63)
p1.myfunc()
# self 参数是对类的当前实例的引用,用于访问属于该类的变量。
不必被命名为 self,但它必须是类中任意函数的首个参数

14.python的小技巧和内置库
(1)输入输出
`# 接收两个值,使用n,m分别接收列表中的两个值,n行的输入,每行m个数字
n, m = [int(x) for x in input().split()]

构造输入列表的列表

num_list = []

for i in range(n):
# python可以不用在意m的值,将所有数值接收进来然后使用len判断长度
tmp_list = [int(x) for x in input().split()]
num_list.append(tmp_list)
`
用列表生成来接收不定量的输入
输出:print函数默认分隔符是换行,end参数来修改输出的结束字符

for i in range(10):
	print(i, end=' ')

生成有初始值的列表:
一维列表(利用乘法生成初始值为False的长度为100的一维列表):
visited = [False] * 100
二维列表(利用列表生成器生成一个n*m的二维的初始值为0的列表):
visited = [[0 for i in range(m)] for j in range(n)]

15.构造二维数组
坑:不能用 [[0]n]n来构造,因为本质是把[0]*n的数组指针复制,更改其中一个其他的都会跟着改变。

posted @ 2023-02-23 16:19  hp12138  阅读(21)  评论(0编辑  收藏  举报