[英]How to separate numbers from an iterable in two lists of even and odd numbers?
The function is supposed to take a list of numbers, and then generate two new lists separating even and uneven numbers in each one. function 应该获取一个数字列表,然后生成两个新列表,将每个列表中的偶数和奇数分开。
def separate(list):
evenList = []
unevenList = []
for e in list:
if e % 2 == 0:
evenList.append(e)
elif e % 1 == 0:
unevenList.append(e)
print(f"The even list is ", evenList)
print(f"The uneven list is ", unevenList)
I notice when my argument ends in an even number, it appends everything into the even list, and same if it ends in an uneven number with the uneven list.我注意到当我的论点以偶数结尾时,它会将所有内容附加到偶数列表中,如果它以奇数结束并带有不均匀列表,则相同。 I just need a way to iterate based on the conditional, and append only those number that meet the criteria to each new list.
我只需要一种方法来根据条件进行迭代,而 append 只有那些符合每个新列表标准的数字。
You can do it with two list comprehensions (also, you shouldn't overwrite the builtin python list
):你可以用两个列表推导来做到这一点(另外,你不应该覆盖内置的 python
list
):
even_lst = [i for i in lst if not i % 2]
odd_lst = [i for i in lst if i % 2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.