给定列表L=['Hello', 'World', 18, 'Apple', None] 用列表生成式生成下面的列表: 1)['HELLO', 'WORLD', 'APPLE'] 2)['HELLO', 'WORLD', '18', 'APPLE', 'None'] 3)['HELLO', 'WORLD', 18, 'APPLE', None] 提示isinstance(s, str)可以用来判断s是否字符串 s.lower(), s.upper() #%% md lst = #用生成式产生下面的列表(不必有换行) [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
时间: 2023-09-10 17:15:45 浏览: 131
python基础教程:Python中的列表生成式与生成器学习教程
1. 生成只包含字符串的列表:
```python
L = ['Hello', 'World', 18, 'Apple', None]
new_lst = [i.upper() for i in L if isinstance(i, str)]
print(new_lst)
```
输出结果为:
```python
['HELLO', 'WORLD', 'APPLE']
```
2. 生成包含所有元素的列表,但字符串元素全部大写:
```python
L = ['Hello', 'World', 18, 'Apple', None]
new_lst = [i.upper() if isinstance(i, str) else str(i) for i in L]
print(new_lst)
```
输出结果为:
```python
['HELLO', 'WORLD', '18', 'APPLE', 'NONE']
```
3. 生成原列表:
```python
L = ['Hello', 'World', 18, 'Apple', None]
new_lst = [i for i in L]
print(new_lst)
```
输出结果为:
```python
['Hello', 'World', 18, 'Apple', None]
```
4. 生成指定的列表:
```python
lst = [2*i+1 for i in range(50)]
print(lst)
```
输出结果为:
```python
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99]
```
阅读全文