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]

内置函数isinstanceissubclass

isinstanceissubclass 是 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:检查一个类是否是另一个类的子类。

列表的常用方法

  1. append(x)

    • 向列表末尾添加一个元素 x
    pythonlst = [1, 2, 3]
    lst.append(4)
    print(lst)  # 输出 [1, 2, 3, 4]
    
  2. extend(iterable)

    • 将另一个可迭代对象中的元素添加到列表末尾。
    pythonlst = [1, 2, 3]
    lst.extend([4, 5])
    print(lst)  # 输出 [1, 2, 3, 4, 5]
    
  3. insert(i, x)

    • 在指定位置 i 插入元素 x
    pythonlst = [1, 2, 4]
    lst.insert(2, 3)
    print(lst)  # 输出 [1, 2, 3, 4]
    
  4. remove(x)

    • 移除列表中第一个匹配元素 x
    pythonlst = [1, 2, 3, 2, 4]
    lst.remove(2)
    print(lst)  # 输出 [1, 3, 2, 4]
    
  5. 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]
    
  6. index(x[, start[, end]])

    • 返回元素 x 在列表中的索引,可选参数 startend 用于指定搜索范围。
    pythonlst = [1, 2, 3, 4, 5]
    index = lst.index(3)
    print(index)  # 输出 2
    
  7. count(x)

    • 返回元素 x 在列表中出现的次数。
    pythonlst = [1, 2, 3, 2, 4]
    count = lst.count(2)
    print(count)  # 输出 2
    
  8. 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]
    
  9. reverse()

    • 反转列表中的元素顺序。
    pythonlst = [1, 2, 3, 4]
    lst.reverse()
    print(lst)  # 输出 [4, 3, 2, 1]
    
  10. copy()

    • 返回列表的一个浅拷贝。
    pythonlst = [1, 2, 3]
    new_lst = lst.copy()
    print(new_lst)  # 输出 [1, 2, 3]
    
  11. clear()

    • 清空列表。
    pythonlst = [1, 2, 3]
    lst.clear()
    print(lst)  # 输出 []
    

字符串的常用方法

  1. capitalize()

    • 将字符串的第一个字符大写,其余字符小写。
    pythons = "hello world"
    print(s.capitalize())  # 输出 "Hello world"
    
  2. upper()

    • 将字符串中的所有字符转换为大写。
    pythons = "hello world"
    print(s.upper())  # 输出 "HELLO WORLD"
    
  3. lower()

    • 将字符串中的所有字符转换为小写。
    pythons = "HELLO WORLD"
    print(s.lower())  # 输出 "hello world"
    
  4. title()

    • 将字符串中的每个单词首字母大写, 其余字母转换为小写。
    pythons = "hello world"
    print(s.title())  # 输出 "Hello World"
    
  5. strip()

    • 去除字符串两端的空白字符(包括空格、制表符、换行符等)。
    pythons = "  hello world  "
    print(s.strip())  # 输出 "hello world"
    
  6. lstrip()

    • 去除字符串左边的空白字符。
    pythons = "  hello world  "
    print(s.lstrip())  # 输出 "hello world  "
    
  7. rstrip()

    • 去除字符串右边的空白字符。
    pythons = "  hello world  "
    print(s.rstrip())  # 输出 "  hello world"
    
  8. startswith(prefix)

    • 检查字符串是否以指定前缀开始。
    pythons = "hello world"
    print(s.startswith("hello"))  # 输出 True
    
  9. endswith(suffix)

    • 检查字符串是否以指定后缀结束。
    pythons = "hello world"
    print(s.endswith("world"))  # 输出 True
    
  10. find(sub)

    • 返回子字符串 sub 在字符串中的起始索引,如果找不到则返回 -1
    pythons = "hello world"
    print(s.find("world"))  # 输出 6
    
  11. rfind(sub)

    • 从右向左搜索子字符串 sub 的起始索引,如果找不到则返回 -1
    pythons = "hello world world"
    print(s.rfind("world"))  # 输出 12
    
  12. replace(old, new[, count])

    • 替换字符串中的子字符串 oldnew,可选参数 count 限制替换次数。
    pythons = "hello world"
    print(s.replace("world", "planet"))  # 输出 "hello planet"
    print(s.replace("o", "O", 1))  # 输出 "heOlo world"
    
  13. split(sep=None, maxsplit=-1)

    • 根据分隔符 sep 将字符串分割成列表,可选参数 maxsplit 限制分割次数。
    pythons = "hello,world,python"
    print(s.split(","))  # 输出 ['hello', 'world', 'python']
    print(s.split(",", 1))  # 输出 ['hello', 'world,python']
    
  14. rsplit(sep=None, maxsplit=-1)

    • 从右向左根据分隔符 sep 将字符串分割成列表,可选参数 maxsplit 限制分割次数。
    pythons = "hello,world,python"
    print(s.rsplit(",", 1))  # 输出 ['hello,world', 'python']
    
  15. join(iterable)

    • 将可迭代对象中的元素连接成一个字符串,中间用指定字符串连接。
    pythonlst = ["hello", "world"]
    print("-".join(lst))  # 输出 "hello-world"
    
  16. isalpha()

    • 检查字符串是否只包含字母。
    pythons = "hello"
    print(s.isalpha())  # 输出 True
    
  17. isdigit()

    • 检查字符串是否只包含数字。
    pythons = "123"
    print(s.isdigit())  # 输出 True
    
  18. isspace()

    • 检查字符串是否只包含空白字符。
    pythons = "   "
    print(s.isspace())  # 输出 True
    
  19. istitle()

    • 检查字符串是否每个单词首字母大写。
    pythons = "Hello World"
    print(s.istitle())  # 输出 True
    
  20. islower()

    • 检查字符串是否所有字母都是小写。
    pythons = "hello"
    print(s.islower())  # 输出 True
    
  21. isupper()

    • 检查字符串是否所有字母都是大写。
    pythons = "HELLO"
    print(s.isupper())  # 输出 True
    
  22. 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."
    
  23. 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值