掌握这些就可以开始刷题了。
列表创建:
#字符串转列表:
list = [i for i in str]
list = list(str) #元组、集合同理
#字典转列表
d = {"a": 1, "b": 2, "c": 3}
keys_list = list(d.keys()) # ['a', 'b', 'c']
values_list = list(d.values()) # [1, 2, 3]
items_list = list(d.items()) # [('a', 1), ('b', 2), ('c', 3)]
#顺序列表:列表推导式
list= [x for x in range(10)] # 输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list = [x for x in range(10) if x %2 == 0] # 输出: [0, 2, 4, 6, 8]
list = [(x,x**2) for x in range(100)] # 输出: [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]
list = [(m,n) for m in li1 for n in li2] #等于zip(li1,li2)
列表常用函数:
#增加元素
list1 = list.append(5) # [1, 2, 3, 4, 5]
list1 = list.extend([6,7]) # [1, 2, 3, 4, 5, 6, 7]
在指定位置插入一个元素:
list1 = list.insert(2,'a') # [1, 2, 'a', 3, 4, 5, 6, 7]
#删除元素
list1 = list.pop()
list1 = list.pop(0)
list1 = list.remove('a') # 移除第一个值为 "a" 的元素
#查找和排序
index = list.index('a') # 返回值为 "a" 的第一个索引
count = my_list.count("a") # 返回 "a" 出现的次数
list1 = list.srot()
list1 = list.sort(reverse = True) # 按降序排序
list1 = list.reverse() 反转列表# [7, 6, 5, 4, 3, 2, 1]
#内置函数
max(list)
min(list)
sum(list)
len(list)
#列表切片
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
获取前三个元素
first_three = my_list[:3] # [0, 1, 2]
获取从索引3到索引6的元素
subset = my_list[3:7] # [3, 4, 5, 6]
获取每隔两个元素的子集
every_other = my_list[::2] # [0, 2, 4, 6, 8]
反转列表
reversed_list = my_list[::-1] # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
#列表复制
list1 = list.copy()
_____________________________________________________________________________
字符串
#字符串创建
s = ''
s = str(列表、元组、字典、集合等)
# 使用 str.format()
name = "Alice"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
# 使用 f-string
message = f"My name is {name} and I am {age} years old."
s = ", ".join(my_list) # "apple, banana, cherry"
s = " ".join(my_tuple) # "John Doe"
字典转换为字符串
my_dict = {"name": "Alice", "age": 25}
keys_str = ", ".join(my_dict.keys()) # "name, age"
values_str = ", ".join(str(v) for v in my_dict.values()) # "Alice, 25"
#字符串常用函数及用法
s.lower()
s.upper()
s.title()
index = s.find('a') #返回a的下标,如果没有a
s.isalpha()
s.isdigit()
s.strip()去掉两端空格
s.rstrip()
s.lstrip()
s = "hello, world!"
new_s = s.replace("world", "Python")
print(new_s) # 输出: "hello, Python!"
字典:
#字典创建
dict = {}
dict1 = dict(name = 'a')
numbers = [1, 2, 3, 4]
squares = {x: x**2 for x in numbers}
#合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
dict1.update(dict2)
print(dict1) 或merged_dict = dict1 | dict2 # 输出: {'a': 1, 'b': 3, 'c': 4}
#遍历字典
for key in my_dict:
print(key) # 输出: name, gender
for value in my_dict.values():
print(value) # 输出: Alice, Female
for key, value in my_dict.items():
print(key, value) # 输出: name Alice, gender Female
#检查键或值是否存在
print("name" in my_dict) # 输出: True
print("age" in my_dict) # 输出: False
print("Alice" in my_dict.values()) # 输出: True
print("USA" in my_dict.values()) # 输出: False
常用内置函数:
len()
keys()
values()
items()
___________________________________________________________________________________
匿名函数用法:
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key = lambda x:len(x))
# 输出: ['date', 'apple', 'cherry', 'banana']
my_dict = {"a": 3, "b": 1, "c": 2}
sorted_dict = sorted(my_dict.items(),key = lambda item: item[1])
# 输出: [('b', 1), ('c', 2), ('a', 3)]
#如何调用类里的方法:
class Solution:
def greet(self, name: str) -> str:
"""返回一个问候语"""
return f"Hello, {name}!"
def add_numbers(self, a: int, b: int) -> int:
"""返回两个数字的和"""
return a + b
# 创建 Solution 类的实例
solution = Solution()
# 调用 greet 方法
greeting = solution.greet("Alice")
print(greeting) # 输出: Hello, Alice!
# 调用 add_numbers 方法
result = solution.add_numbers(5, 3)
print(result) # 输出: 8
———————————————————————————————————————————
python刷题常见运行错误:
1、ValueError: invalid literal for int() with base 10: 'some_string'
例如:
s = "abc"
n = int(s) # 会抛出 ValueError: invalid literal for int() with base 10: 'abc'
在调用 int() 之前,检查字符串是否只包含数字。可以使用 str.isdigit() 方法
s = "123"
if s.isdigit():
n = int(s)
print(n)
else:
print("The string is not a valid integer.")
2、在 Python 中,IndentationError: unexpected indent 是一个常见的语法错误,表示代码的缩进不正确。
如果代码行被错误地缩进,而它不应该缩进,就会出现 unexpected indent 错误。
#分类报错:
1. 语法错误(SyntaxError)
语法错误是 Python 解释器在解析代码时发现的错误,通常是由于拼写错误、缺少括号、缩进不正确等引起的
2. 类型错误(TypeError)
类型错误是由于尝试对不兼容的类型执行操作时引发的。如字符串与数字拼接、不匹配的操作。
3. 名称错误(NameError)
名称错误是由于尝试访问一个未定义的变量或函数时引发的。如拼写错误、变量未定义。
4. 索引错误(IndexError)
索引错误是由于尝试访问列表、字符串或其他序列中不存在的索引时引发的。越界访问、空列表或字符串
5. 值错误(ValueError)
值错误是由于函数接收到的参数值不正确时引发的
6. 键错误(KeyError)
键错误是由于尝试访问字典中不存在的键时引发的。
7. 零除错误(ZeroDivisionError)
零除错误是由于尝试除以零时引发的。
8. 缩进错误(IndentationError)
缩进错误是由于代码块的缩进不正确或不一致时引发的。
9. 文件错误(FileNotFoundError)
文件错误是由于尝试打开或读取不存在的文件时引发的。
10. 逻辑错误(Logical Error)
逻辑错误是代码运行没有报错,但结果不符合预期。这类错误通常是最难调试的。


被折叠的 条评论
为什么被折叠?



