一些 python 语法

Python pip

Posted by gomyck on August 8, 2023

1.Extended Unpacking(扩展解包):除了单个的 * 解包外,还可以使用 ** 来解包字典。这在函数调用时可以用于传递关键字参数。

1
2
3
4
5
def my_function(x, y, z):
    print(x, y, z)

my_dict = {'x': 1, 'y': 2, 'z': 3}
my_function(**my_dict)  # 将字典的键值对作为关键字参数传递给函数

2.Unpacking in List Comprehensions(列表推导式中的解包):你可以在列表推导式中使用解包语法来生成新的列表。

1
2
3
list_of_tuples = [(1, 2), (3, 4), (5, 6)]
flattened_list = [x for pair in list_of_tuples for x in pair]
print(flattened_list)  # 输出: [1, 2, 3, 4, 5, 6]

3.Swapping Variables(变量交换):使用解包可以非常简洁地交换两个变量的值。

1
2
3
4
a = 5
b = 10
a, b = b, a  # 交换a和b的值
print(a, b)  # 输出: 10, 5

4.Unpacking in Function Returns(函数返回中的解包):函数可以返回元组,然后在接收返回值时使用解包。

1
2
3
4
5
def my_function():
    return 1, 2, 3

x, y, z = my_function()  # 将函数返回的元组解包
print(x, y, z)  # 输出: 1, 2, 3

5.Extended Iterable Unpacking(扩展可迭代对象解包):Python 3.10 引入了更灵活的解包语法,可以在可迭代对象中使用 * 语法。

1
2
first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last)  # 输出: 1 [2, 3, 4] 5

6.Comprehensions with Conditionals(带条件的推导式):列表推导式和字典推导式可以包含条件语句,以过滤元素或键值对。

1
2
3
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [x ** 2 for x in numbers if x % 2 == 0]
print(even_squares)  # 输出: [4, 16, 36]

7.enumerate() 函数:enumerate() 可以在迭代时同时获得元素和索引。

1
2
3
4
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
    print(index, fruit)

8.exec() 和 eval() 函数:exec() 用于执行动态生成的Python代码,eval() 用于计算动态生成的表达式的值。

1
2
3
4
5
6
dynamic_code = "print('Hello, dynamic world!')"
exec(dynamic_code)

dynamic_expression = "2 + 3"
result = eval(dynamic_expression)
print(result)  # 输出: 5

9.条件表达式的三目

1
2
3
4
5
x = 10
y = 20

max_value = x if x > y else y
print(max_value)  # 输出: 20