python 3.x : How to extract even numbers from a user input list?

标签 python list python-3.x

我是 Python 的新手,我正在尝试创建仅从用户输入的列表中返回偶数的代码。

我很早就创建了这个:

nums = input('Enter a sequence of numbers separated by commas: ')
lst = str.split(nums)
print(lst)

这会返回用户提供的内容,但逗号仍会出现在结果中。例如,如果我输入: 5, 6, 7 ;它会以 ['5,' , '6,' , '7'] 的形式出现 除了解决这个问题之外,我只想显示偶数。我知道我必须使用 %2 == 0 检查这个,但我不知道我将如何实现它。

最佳答案

首先,您需要将所有字符串项转换为整数。您可以使用 map 高效地完成此操作。之后,您需要做的就是过滤奇数。

filter(lambda x: x % 2 == 0, map(int, str.split(nums, ',')))

如果您使用的是 python3,请使用 list() 将输出转换为列表。


演示:

>>> string = '2,5,8,12,5,6,7'
>>> list(filter(lambda x: x % 2 == 0, map(int, str.split(string, ','))))
[2, 8, 12, 6]

关于 python 3.x : How to extract even numbers from a user input list?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44876704/

相关文章:

python - 如何将 Pandas 数据框显示到现有的 flask html 表中?

python - 使用列表位置中包含的项目进行计算(遗传算法适合度)

java - 在不同列表之间移动属性

java - 在某个值之后搜索列表中的最小元素

python - 如何在python3中读取超时的单个键输入?

python - 无法使用 pyside2 和 QtDesigner 在我的主窗口中导入我的小部件

algorithm - 一跳飞行挑战

python - 如何获取正则表达式最后一场比赛的位置?

python - 如何使用 python BST 实现 'range'

python - 如何选择 numpy 数组中的行索引?