将List拆分为python中的多个列表的有效方法是什么?

时间:2015-09-22 02:04:24

标签: python

我想根据某个表达式将List拆分为多个List。

例如:

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的东西,其复杂度为O(1)?

或者是否有其他收藏可以做到?

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您可以使用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]

这是pythonic的做法(对于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]

答案 1 :(得分:1)

首先,here是一个很好的备忘单,用于Python中各种操作的时间复杂性。

鉴于您对我的陈述的最后回复,我假设您想要将给定列表消费并拆分为三个单独的列表,而不通过理解创建任何中间列表。实现此目的的一种方法是将数据结构更改为collections.deque,因为list.remove()需要O(n) (因为它需要转换元素)deque.popleft()需要O(1)

>>> def partition(queue):
...     partition1, partition2, partition3 = [], [], []
...     while queue:
...         ele = queue.popleft()
...         if 0 < ele <= 3:
...             partition1.append(ele)
...         elif 3 < ele <= 6:
...             partition2.append(ele)
...         else:
...             partition3.append(ele)
...     return partition1, partition2, partition3 

>>> import collections
>>> p1, p2, p3 = partition(collections.deque(range(10)))

>>> print p1
[1, 2, 3]

>>> print p2
[4, 5, 6]

>>> print p3
[0, 7, 8, 9]