python - 编写一行代码以获取单独数组中的奇数和偶数

标签 python algorithm

我在 tcs codevita 采访中被问到这个问题。给定一个数组

a = [1,2,3,4,5,6,7,8,9,10]

你必须在Python中编写一行代码,这样你就可以得到2个不同的数组/列表,其中一个包含奇数,另一个包含偶数。即一个列表

odd = [1,3,5,7,9]

以及其他列表

even =[2,4,6,8,10]

我无法在一行中编写此代码。谁能告诉我如何在一行中解决这个问题?

最佳答案

您可以在一行中使用两个列表推导式:

odd, even = [el for el in a if el % 2==1], [el for el in a if el % 2==0]

print(odd, even)
#([1, 3, 5, 7, 9], [2, 4, 6, 8, 10])

关于python - 编写一行代码以获取单独数组中的奇数和偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52014450/

相关文章:

python - 属性错误: module 'jaxlib.xla_extension' has no attribute 'PmapFunction'

python - 当多个UI元素具有相同的UI元素时如何识别UI元素

python - python并发下载和处理大文件

C++如何在不使用排序的情况下打印大小为n的数组中的最小数字

algorithm - 伪代码解释器?

php - 查看我的数字是否在范围数组中的最佳算法是什么?

javascript - 将 python TensorFlow Layers 模型加载到 JavaScript 中

python - 具有定义字节顺序的 Numpy tobytes()

java - 解析包含分隔符的字符串

c - 合并排序未显示正确的输出