输入一个包含若干整数的列表,输出一个新列表,要求性能列表中只包含原列表中的偶数。
时间: 2023-07-16 19:13:08 浏览: 43
可以使用列表推导式来实现:
```python
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_list = [x for x in original_list if x % 2 == 0]
print(even_list)
```
输出:
```
[2, 4, 6, 8]
```
这里,我们首先定义了一个原始列表 `original_list`,包含若干整数。然后,我们使用列表推导式筛选出其中的偶数,生成一个新列表 `even_list`。在列表推导式中,`if x % 2 == 0` 表示只选择能被 2 整除的元素。
相关问题
编写Python程序,输入一个包含若干整数的列表,输出一个新列表,要求性能列表中只包含原列表中的偶数。
好的,以下是一个简单的 Python 程序,可以实现你的需求:
```python
# 输入列表
lst = list(map(int, input("请输入一个包含若干整数的列表,以空格分隔:").split()))
# 生成新列表
new_lst = [x for x in lst if x % 2 == 0]
# 输出新列表
print("新列表:", new_lst)
```
以上代码中,`input()` 函数用于接收用户输入的整数列表,`map()` 函数将输入的字符串列表转换为整数列表,`split()` 函数用于按空格将字符串分割成列表。接下来,使用列表推导式生成一个新列表,其中只包含原列表中的偶数。最后,使用 `print()` 函数输出新列表。
运行程序,输入一个包含若干整数的列表,就可以输出只包含偶数的新列表了。
python编写程序,输入一个包含若干整数的列表,输出一个新列表,要求性能列表中只包含原列表中的偶数
可以使用列表推导式来实现这个功能。具体代码如下:
```python
lst = [int(x) for x in input("请输入一个包含若干整数的列表,用空格分隔: ").split()]
new_lst = [x for x in lst if x % 2 == 0]
print(new_lst)
```
代码中使用 `input` 函数获取用户输入的列表,然后使用 `split` 方法将字符串按空格分隔成一个列表。接着使用列表推导式生成一个新列表,其中只包含原列表中的偶数。最后输出新列表即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)