我在 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/