python一行代码for循环的例子有哪些?

bluesky1年前 ⋅ 700 阅读
1. 打印数字 0 到 9:

```python
[print(i) for i in range(10)]
```

2. 将列表中的所有元素平方:

```python
lst = [1, 2, 3, 4, 5]
squares = [i**2 for i in lst]
```

3. 求列表中的最大值:

```python
lst = [10, 20, 30, 25, 15]
max_value = max(lst)
```

4. 求列表中的偶数:

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

5. 对字符串中的字符进行排序:

```python
string = "hello world"
sorted_str = ''.join(sorted(string))
```

全部评论: 0

    相关推荐