简体   繁体   English

如何在偶数和奇数的两个列表中将数字与可迭代对象分开?

[英]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.

相关问题 将奇数和偶数分离到单独的列表中-更简洁的方法? - Segregating odd and even numbers into separate lists - a more concise approach? 在 Python 中使用两个单独的线程打印偶数和奇数 - Printing even and odd numbers using two separate threads in Python 如何在跳过数字时通过搜索数组分隔奇数和偶数范围 - How to Separate a Range of Odd and Even Numbers Through Searching the Array While Skipping Numbers 如何检查Iterable中是否有任何奇数/偶数(例如列表/元组)? - How to check if there's any odd/even numbers in an Iterable (e.g. list/tuple)? 我如何总结两个数字之间的所有偶数和奇数? - How would I sum up all the even and odd numbers between two numbers? Python 2奇数或偶数 - Python 2 Odd or Even numbers 列表中的奇数和偶数 - Odd and Even numbers in list 在给定条件奇数或偶数的情况下,如何对列表中的偶数或奇数求和? - How to sum even or odd numbers in a list given the condition odd or even? 如何将列表从对偶数和奇数说 true/false 更改为简单地对每个数字说偶数或奇数? - How to change a list from saying true/false for even and odd numbers , to simply saying even or odd for each number? 给定两个数字列表创建一个新列表,它应该只包含第一个列表中的奇数和第二个列表中的偶数 - Given two list of numbers create a new list and it should contain only odd numbers from the first list # and even numbers from the second list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM