有哪些非常实用的单行 Python 代码?

bluesky1年前 ⋅ 704 阅读
以下是一些非常实用的单行 Python 代码:

1. 列表反转

```python
lst = [1, 2, 3, 4, 5]
lst[::-1]
```

2. 合并字符串

```python
lst = ['hello', 'world']
' '.join(lst)
```

3. 计算列表中元素的出现次数

```python
lst = [1, 2, 3, 1, 2, 3, 4]
{k: lst.count(k) for k in set(lst)}
```

4. 找出列表中的偶数

```python
lst = [1, 2, 3, 4, 5, 6]
[x for x in lst if x % 2 == 0]
```

5. 读取文件内容

```python
with open('filename') as f:
    contents = f.read()
```

6. 判断一个字符串是否是数字

```python
str.isdigit()
```

7. 使用 lambda 函数进行排序

```python
lst = [(1, 5), (3, 3), (2, 8)]
sorted(lst, key=lambda x: x[1])
```

8. 链接两个字典

```python
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
{**dict1, **dict2}
```

9. 计算列表中的平均值

```python
lst = [1, 2, 3, 4, 5]
sum(lst) / len(lst)
```

10. 简单的数据清洗

```python
text = 'Hello, World!'
''.join(filter(str.isalpha, text)).lower()
```

全部评论: 0

    相关推荐