此代码使用了在此 URL 中找到的概念:
Python list comprehension- "pop" result from original list?
将此处找到的一个有趣概念应用于您的问题,以下是迄今为止其他人针对此问题发布的一些替代方法。两者都使用列表推导,并被注释以解释第二个选项与第一个选项的目的。作为我学习曲线的一部分,为我做了这个实验,但希望它也可以帮助你和这个线程上的其他人:
这些的好处在于,如果您的输入列表非常大,您不必将内存消耗翻倍即可完成工作。当你缩小另一个时,你建立一个。
此代码已在 Python 2.7 和 Python 3.6 上测试:
o1 = [1,5,8,-3,6,9,-4,2,-5,6,7,-7, 999, -43, -1, 888]
# modified version of poster's list
o1b = [1,5,8,-3,6,8,-3,2,-4,6,8] # poster's list
o2 = [x for x in (o1.pop() for i in range(len(o1))) \
if (lambda x: True if x < 0 else o1.insert(0, x))(x)]
o2b = [x for x in (o1b.pop() for i in range(len(o1b))) \
if (lambda x: True if x < 0 else o1b.insert(0, x))(x)]
print(o1)
print(o2)
print("")
print(o1b)
print(o2b)
它产生这样的结果集(在 iPython Jupyter Notebooks 上):
[1, 5, 8, 6, 9, 2, 6, 7, 999, 888]
[-1, -43, -7, -5, -4, -3]
[1, 5, 8, 6, 8, 2, 6, 8]
[-4, -3, -3]
这是另一个版本,它也使用列表推导作为工作工具,但以更易读(我认为)和更容易使用不同数字列表进行测试的方式对代码进行了功能化。有些人可能更喜欢原始代码,因为它更短:
p1 = [1,5,8,-3,6,9,-4,2,-5,6,7,-7, 999, -43, -1, 888]
# modified version of poster's list
p1b = [1,5,8,-3,6,8,-3,2,-4,6,8] # poster's list
def lst_mut_byNeg_mod(x, pLst): # list mutation by neg nums module
# this function only make sense in context of usage in
# split_pos_negs_in_list()
if x < 0: return True
else:
pLst.insert(0,x)
return False
def split_pos_negs_in_list(pLst):
pLngth = len(pLst) # reduces nesting of ((()))
return [x for x in (pLst.pop() for i in range(pLngth)) \
if lst_mut_byNeg_mod(x, pLst)]
p2 = split_pos_negs_in_list(p1)
print(p1)
print(p2)
print("")
p2b = split_pos_negs_in_list(p1b)
print(p1b)
print(p2b)
最后的想法:
之前提供的链接在评论线程中有很多想法:
- 它建议 Google 搜索“python 布隆过滤器库” - 从性能的角度来看,这听起来很有希望,但我还没有研究过
- 该线程上有一个帖子,有 554 人赞成,但它至少有 4 个 cmets 解释了它可能有什么问题。在探索选项时,建议扫描评论线索,而不仅仅是查看获得最多选票的内容。针对此类情况提出了许多选项。