Python: split a list based on a condition?

前端 未结 30 2458
误落风尘
误落风尘 2020-11-22 06:56

What\'s the best way, both aesthetically and from a performance perspective, to split a list of items into multiple lists based on a conditional? The equivalent of:

30条回答
  •  暖寄归人
    2020-11-22 07:08

    good.append(x) if x in goodvals else bad.append(x)
    

    This elegant and concise answer by @dansalmo showed up buried in the comments, so I'm just reposting it here as an answer so it can get the prominence it deserves, especially for new readers.

    Complete example:

    good, bad = [], []
    for x in my_list:
        good.append(x) if x in goodvals else bad.append(x)
    

提交回复
热议问题