在Python中,一行代码可以用来完成多种任务,例如:
1. 交换两个变量的值:
```python
a, b = 5, 10; a, b = b, a; print(a, b) 输出: 10 5
```
2. 生成列表的反转版本:
```python
lst = [1, 2, 3, 4, 5]; reversed_lst = lst[::-1]; print(reversed_lst) 输出: [5, 4, 3, 2, 1]
```
3. 计算列表中所有数字的平方和:
```python
squared_sum = sum(x2 for x in [1, 2, 3, 4, 5]); print(squared_sum) 输出: 55
```
4. 生成斐波那契数列:
```python
fib = lambda n: n if n <= 1 else fib(n-1) + fib(n-2); print([fib(i) for i in range(10)]) 输出: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
```
5. 交换两个变量的值(另一种方法):
```python
a = 4; b = 5; a, b = b, a; print(a, b) 输出: 5 4
```
6. 多个变量赋值:
```python
a, b, c = 4, 5.5, 'Hello'; print(a, b, c) 输出: 4 5.5 Hello
```
7. 列表中偶数的和:
```python
a = [1, 2, 3, 4, 5, 6]; s = sum([num for num in a if num % 2 == 0]); print(s) 输出: 12
```
8. 从列表中删除多个元素:
```python
a = [1, 2, 3, 4, 5]; a = a[1::2]; print(a) 输出: [1, 3, 5]
```
9. 读取文件:
```python
lst = [line.strip() for line in open('data.txt')]; print(lst)
```
10. 打印一行代码:
```python
print("Hello, World!")
```
这些示例展示了Python中一行代码的多样性和强大功能。根据具体需求,可以选择合适的方法来简化代码编写。