gpt4 book ai didi

python - 在 python 中将一个列表拆分为多个列表的有效方法是什么

转载 作者:太空宇宙 更新时间:2023-11-04 01:01:22 24 4
gpt4 key购买 nike

我想根据某些表达式将一个列表拆分为多个列表。

例如:

for elem in elemList:
if elem>0 and elem<=3 add element to Partition1
if elem>3 and elem<=6 add element to Partition2
else add element to Partition3

如何高效地做到这一点?C++中有没有像erase、push_back in list之类复杂度为O(1)的?

或者有其他一些集合可以做到吗?

最佳答案

如果我理解正确,你可以使用list comprehensions :

Partition1 = [elem for elem in elemList if elem <= 3]
Partition2 = [elem for elem in elemList if elem > 3 and elem <= 6]
Partition3 = [elem for elem in elemList if elem > 6]

这是 Python 式的做法(对于 Partition1):

Partition1 = [] # creates an empty list
for elem in elemList: # for each element in list
if elem > 0 and elem <= 3: # if they satisfy the condition
Partition1.append(elem) # append them to the list

编辑:我在上面假设所有元素都大于零...如果其中一些不是,则 Partition1 和 Partition3 的列表理解必须是:

Partition1 = [elem for elem in elemList if elem > 0 and elem <= 3]
Partition3 = [elem for elem in elemList if elem > 6 or elem <= 0]

关于python - 在 python 中将一个列表拆分为多个列表的有效方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32707273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com