python语言基础杂谈
内置函数map
map
是 Python 中的一个内置函数,用于将一个函数应用到一个可迭代对象(如列表、元组)中的每一个元素,并返回一个迭代器。
map(function, iterable, ...)
function
: 要应用到每个元素上的函数。
iterable
: 可迭代对象,可以是列表、元组等。如果传入多个可迭代对象,function
必须能够接收相应数量的参数。
>>> a = map(lambda x : x**3, [1, 2, 3])
>>> list(a)
[1, 8, 27]
内置函数filter
filter()
函数是 Python 中的一个内置函数,用于根据某个条件过滤序列中的元素。它返回一个迭代器,其中包含满足条件的所有元素。
filter(function, iterable)
function
: 要应用到每个元素上的函数。
iterable
: 可迭代对象,可以是列表、元组等。如果传入多个可迭代对象,function
必须能够接收相应数量的参数。
numbers = [1, 2, 3, 4, 5, 6]
# 使用 lambda 表达式过滤偶数
filtered_numbers = filter(lambda x: x % 2 == 0, numbers)
# 将结果转换为列表
result = list(filtered_numbers)
print(result) # 输出 [2, 4, 6]
内置函数isinstance
和issubclass
isinstance
和 issubclass
是 Python 中常用的类型检查函数,它们分别用于检查对象的类型和类之间的继承关系。下面详细介绍这两个函数的用法和区别。
isinstance
函数
isinstance
用于检查一个对象是否是某个类的实例或者其子类的实例。
isinstance(object, class_or_tuple)
参数
- object:要检查的对象。
- class_or_tuple:一个类或类的元组。如果是元组,可以同时检查多个类。
示例
class A:
pass
class B(A):
pass
a_instance = A()
b_instance = B()
print(isinstance(a_instance, A)) # 输出 True
print(isinstance(b_instance, A)) # 输出 True
print(isinstance(b_instance, B)) # 输出 True
print(isinstance("hello", str)) # 输出 True
print(isinstance(123, (int, float))) # 输出 True
issubclass
函数
issubclass
用于检查一个类是否是另一个类的子类。
issubclass(class, class_or_tuple)
- class:要检查的类。
- class_or_tuple:一个类或类的元组。如果是元组,可以同时检查多个类。
class A:
pass
class B(A):
pass
class C:
pass
print(issubclass(B, A)) # 输出 True
print(issubclass(A, object)) # 输出 True
print(issubclass(C, A)) # 输出 False
print(issubclass(int, (int, float))) # 输出 True
isinstance
:检查一个对象是否是某个类的实例或其子类的实例。
issubclass
:检查一个类是否是另一个类的子类。
列表的常用方法
-
append(x)
:- 向列表末尾添加一个元素
x
。
pythonlst = [1, 2, 3] lst.append(4) print(lst) # 输出 [1, 2, 3, 4]
- 向列表末尾添加一个元素
-
extend(iterable)
:- 将另一个可迭代对象中的元素添加到列表末尾。
pythonlst = [1, 2, 3] lst.extend([4, 5]) print(lst) # 输出 [1, 2, 3, 4, 5]
-
insert(i, x)
:- 在指定位置
i
插入元素x
。
pythonlst = [1, 2, 4] lst.insert(2, 3) print(lst) # 输出 [1, 2, 3, 4]
- 在指定位置
-
remove(x)
:- 移除列表中第一个匹配元素
x
。
pythonlst = [1, 2, 3, 2, 4] lst.remove(2) print(lst) # 输出 [1, 3, 2, 4]
- 移除列表中第一个匹配元素
-
pop([i])
:- 移除并返回指定位置
i
的元素,默认移除并返回最后一个元素。
pythonlst = [1, 2, 3, 4] x = lst.pop() # 移除并返回 4 print(lst) # 输出 [1, 2, 3] y = lst.pop(1) # 移除并返回 2 print(lst) # 输出 [1, 3]
- 移除并返回指定位置
-
index(x[, start[, end]])
:- 返回元素
x
在列表中的索引,可选参数start
和end
用于指定搜索范围。
pythonlst = [1, 2, 3, 4, 5] index = lst.index(3) print(index) # 输出 2
- 返回元素
-
count(x)
:- 返回元素
x
在列表中出现的次数。
pythonlst = [1, 2, 3, 2, 4] count = lst.count(2) print(count) # 输出 2
- 返回元素
-
sort(key=None, reverse=False)
:- 对列表进行排序,可选参数
key
用于自定义排序规则,reverse
用于反转排序。
pythonlst = [3, 1, 4, 2] lst.sort() print(lst) # 输出 [1, 2, 3, 4] lst.sort(reverse=True) print(lst) # 输出 [4, 3, 2, 1]
- 对列表进行排序,可选参数
-
reverse()
:- 反转列表中的元素顺序。
pythonlst = [1, 2, 3, 4] lst.reverse() print(lst) # 输出 [4, 3, 2, 1]
-
copy()
:- 返回列表的一个浅拷贝。
pythonlst = [1, 2, 3] new_lst = lst.copy() print(new_lst) # 输出 [1, 2, 3]
-
clear()
:- 清空列表。
pythonlst = [1, 2, 3] lst.clear() print(lst) # 输出 []
字符串的常用方法
-
capitalize()
:- 将字符串的第一个字符大写,其余字符小写。
pythons = "hello world" print(s.capitalize()) # 输出 "Hello world"
-
upper()
:- 将字符串中的所有字符转换为大写。
pythons = "hello world" print(s.upper()) # 输出 "HELLO WORLD"
-
lower()
:- 将字符串中的所有字符转换为小写。
pythons = "HELLO WORLD" print(s.lower()) # 输出 "hello world"
-
title()
:- 将字符串中的每个单词首字母大写, 其余字母转换为小写。
pythons = "hello world" print(s.title()) # 输出 "Hello World"
-
strip()
:- 去除字符串两端的空白字符(包括空格、制表符、换行符等)。
pythons = " hello world " print(s.strip()) # 输出 "hello world"
-
lstrip()
:- 去除字符串左边的空白字符。
pythons = " hello world " print(s.lstrip()) # 输出 "hello world "
-
rstrip()
:- 去除字符串右边的空白字符。
pythons = " hello world " print(s.rstrip()) # 输出 " hello world"
-
startswith(prefix)
:- 检查字符串是否以指定前缀开始。
pythons = "hello world" print(s.startswith("hello")) # 输出 True
-
endswith(suffix)
:- 检查字符串是否以指定后缀结束。
pythons = "hello world" print(s.endswith("world")) # 输出 True
-
find(sub)
:- 返回子字符串
sub
在字符串中的起始索引,如果找不到则返回-1
。
pythons = "hello world" print(s.find("world")) # 输出 6
- 返回子字符串
-
rfind(sub)
:- 从右向左搜索子字符串
sub
的起始索引,如果找不到则返回-1
。
pythons = "hello world world" print(s.rfind("world")) # 输出 12
- 从右向左搜索子字符串
-
replace(old, new[, count])
:- 替换字符串中的子字符串
old
为new
,可选参数count
限制替换次数。
pythons = "hello world" print(s.replace("world", "planet")) # 输出 "hello planet" print(s.replace("o", "O", 1)) # 输出 "heOlo world"
- 替换字符串中的子字符串
-
split(sep=None, maxsplit=-1)
:- 根据分隔符
sep
将字符串分割成列表,可选参数maxsplit
限制分割次数。
pythons = "hello,world,python" print(s.split(",")) # 输出 ['hello', 'world', 'python'] print(s.split(",", 1)) # 输出 ['hello', 'world,python']
- 根据分隔符
-
rsplit(sep=None, maxsplit=-1)
:- 从右向左根据分隔符
sep
将字符串分割成列表,可选参数maxsplit
限制分割次数。
pythons = "hello,world,python" print(s.rsplit(",", 1)) # 输出 ['hello,world', 'python']
- 从右向左根据分隔符
-
join(iterable)
:- 将可迭代对象中的元素连接成一个字符串,中间用指定字符串连接。
pythonlst = ["hello", "world"] print("-".join(lst)) # 输出 "hello-world"
-
isalpha()
:- 检查字符串是否只包含字母。
pythons = "hello" print(s.isalpha()) # 输出 True
-
isdigit()
:- 检查字符串是否只包含数字。
pythons = "123" print(s.isdigit()) # 输出 True
-
isspace()
:- 检查字符串是否只包含空白字符。
pythons = " " print(s.isspace()) # 输出 True
-
istitle()
:- 检查字符串是否每个单词首字母大写。
pythons = "Hello World" print(s.istitle()) # 输出 True
-
islower()
:- 检查字符串是否所有字母都是小写。
pythons = "hello" print(s.islower()) # 输出 True
-
isupper()
:- 检查字符串是否所有字母都是大写。
pythons = "HELLO" print(s.isupper()) # 输出 True
-
format(\*args, \**kwargs)
:- 格式化字符串。
pythonname = "Alice" age = 30 print("My name is {} and I am {} years old.".format(name, age)) # 输出 "My name is Alice and I am 30 years old."
-
format_map(mapping)
:- 使用映射对象格式化字符串。
pythondata = {"name": "Alice", "age": 30} print("My name is {name} and I am {age} years old.".format_map(data)) # 输出 "My na
字典的get()方法
Python 中的 get()
方法是字典对象的一个方法,用于安全地获取字典中指定键对应的值。如果键不存在,get()
方法会返回一个默认值(默认情况下为 None
),而不会引发 KeyError
异常。
info = {'name':'班长', 'id':100, 'sex':'f', 'address':'北京'}
age = info.get('age')
print(age) # 输出为None
age=info.get('age',18)
print(age) # 输出为18
列表切片越界
当你使用列表切片时,如果切片的起始索引或结束索引超出了列表的范围,Python 不会引发 IndexError
,而是返回一个合理的子列表。这可能导致结果是一个空列表 []
。
my_list = [1, 2, 3, 4, 5]
# 这里切片的起始索引是 10,超出了列表长度
slice_result = my_list[10:15]
print(slice_result) # 输出: []
乘法操作
- 字符串、列表、元组、字节串 和 字节数组 支持乘法操作,用于重复序列。
- 范围对象、集合 和 字典 不支持乘法操作。
s = "hello"
print(s * 3) # 输出 "hellohellohello"
lst = [1, 2, 3]
print(lst * 3) # 输出 [1, 2, 3, 1, 2, 3, 1, 2, 3]
t = (1, 2, 3)
print(t * 3) # 输出 (1, 2, 3, 1, 2, 3, 1, 2, 3)
布尔运算
and
操作符的优先级高于 or
操作符。
空字符串 ''
在布尔上下文中被视为 False
,非空字符串 ' '
在布尔上下文中被视为 True
。
a = 0 or 1 and True
print(a) # 输出 True
str1 = ''
str2 = ' '
if not str1:
print(1)
elif not str2:
print(2)
else:
print(0)
# 输出为1
关键字pass的使用
pass
关键字:表示一个空的代码块,不执行任何操作。作为占位符、空函数或类定义、循环体为空、异常处理等。保持代码结构完整,但实际不执行任何操作。
for i in range(5):
if i == 2:
pass
print(i)
# 输出为: 0 1 2 3 4