Python列表理解-"pop"原始清单的结果? [英] Python list comprehension- "pop" result from original list?

查看:60
本文介绍了Python列表理解-"pop"原始清单的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在Python 3.X中有一个列表.我使用列表推导来返回该列表的子集---是否有一种简单的/Python方式将该子集从原始列表中弹出"(因此返回后,该子集中的元素不再位于原始列表中) ?谢谢!

Say I have a list in Python 3.X. I use list comprehension to return a subset of that list--- is there an easy/Pythonic way to "pop" that subset off of the original list (so the elements in that subset are no longer in the original list after being returned)? Thanks!

示例(我需要定义my_func的帮助):

Example (I need help in defining my_func):

a = [1, 2, 2, 3, 4, 5]
a, b = my_func(a, *kwargs)

然后我想要:

a = [1、2、2]
b = [3,4,5]

a = [1, 2, 2]
b = [3, 4, 5]

注意:我不想一次弹出一个值,而是一次弹出整个子集. 流行"可能不是最好的术语,但我不知道是什么.

Note: I do not want to pop the values off one at a time, but rather the whole subset at once. "Pop" may not be the best terminology, but I don't know what is.

我想到的最好的方法是:

The best way I can think of doing it is:

 temp = [idx for idx, val in enumerate(a) if val > 2]  
 b = [a[i] for i in temp]  
 a = [val for idx,val in enumerate(a) if idx not in temp]  

很显然,我希望有一些更优雅,更高效的东西. 我想避免两次浏览该列表.

Obviously, I would prefer something more elegant and efficient. I want to avoid going over the list twice.

我认为这个问题是唯一的,因为我不仅仅关心拆分列表-我想修改原始列表.将这些拆分中的一个拆分并分配给原始列表变量是一种可能的解决方案,但我希望可能有一种方法,而无需显式分配给原始列表变量(类似于类似b.append(a.pop( )))

I think this question is unique because I am not simply concerned with splitting the list - I want to modify the original list. Splitting and assigning one of those splits to the original list variable is a possible solution, but I was hoping there might be a way to do it without explicitly assigning to the original list variable (similar to something like b.append(a.pop()))

推荐答案

只需使用列表理解功能过滤掉不需要的项目:

Just filter out the unwanted items using list comprehension:

a = [1, 2, 2, 3, 4, 5]
condition = lambda x: x > 2
b = [x for x in a if condition(x)]      # b == [3, 4, 5] 
a = [x for x in a if not condition(x)]  # a == [1, 2, 2]

更新

如果您担心效率问题,那么这是另一种只扫描列表一次的方法:

Update

If you are worrying about efficiency then here is another approach which scans the list only once:

def classify(iterable, condition):
    """ Returns a list that matches the condition and a list that
    does not """
    true_list = []
    false_list = []
    for item in iterable:
        if condition(item):
            true_list.append(item)
        else:
            false_list.append(item)
    return true_list, false_list

a = [1, 2, 2, 3, 4, 5]
b, a = classify(a, lambda x: x > 2)
print(a)  # [1, 2, 2]
print(b)  # [3, 4, 5]

更新2

我没有意识到我的更新看上去与user3467349的更新几乎相同,但是无论您是否相信,我都没有作弊:-)

Update 2

I did not realize that my update looks almost the same to that of user3467349, but believe it or not, I did not cheat :-)

这篇关于Python列表理解-"pop"原始清单的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆