[英]lstrip(), rstrip() for lists
I have a bunch of huge lists with integers. 我有一堆带有整数的巨大列表。 These lists may start or end with a couple of zeroes.
这些列表可以以几个零开始或结束。
Is there an easy way for strip either the zeroes on the left or right side from the list? 是否有一种简单的方法可以从列表中删除左侧或右侧的零? Something analogous to
lstrip()
or rstrip()
for strings? 类似于
lstrip()
或rstrip()
的字符串?
The data looks like 数据看起来像
[0,0,0,1,2,3,4]
or 要么
[1,2,3,4,0,0,0]
I must be able to individually lstrip()
or rstrip()
. 我必须能够单独使用
lstrip()
或rstrip()
。 I do not need a strip from both sides of the list. 我不需要列表两边的条带。
You could use itertools.dropwhile()
: 你可以使用
itertools.dropwhile()
:
>>> L = [0, 0, 1, 1, 2, 2, 0]
>>> list(itertools.dropwhile(lambda x: x == 0, L))
[1, 1, 2, 2, 0]
There is a more efficient solution than the built-in itertools.dropwhile()
. 有一个比内置的
itertools.dropwhile()
更有效的解决方案。 You can use the almighty collections.deque
, which would be the ideal data structure for this task, because its left or right pop
is O(1)
. 您可以使用全能的
collections.deque
,这将是此任务的理想数据结构,因为它的左或右pop
是O(1)
。 Here is the left-strip case, and the right-strip is going to be just the mirror image of it: 这是左边的条纹,右边的条纹只是它的镜像:
from collections import deque
def noLeadingZero(l):
d = deque(l)
for e in l:
if e == 0:
d.popleft()
else:
break
return list(d)
l = [0, 0, 1, 1, 2, 2, 0]
print(noLeadingZero(l))
# Result:
# [1, 1, 2, 2, 0]
Let's test its performance against the following code that utilizes the built-in itertools.dropwhile()
: 让我们根据以下使用内置
itertools.dropwhile()
代码测试其性能:
from itertools import dropwhile
print(list(dropwhile(lambda x: x == 0, l)))
Here is the performance test: 这是性能测试:
import timeit
print timeit.timeit(
setup= """from itertools import dropwhile
l = [0, 0, 1, 1, 2, 2, 0]""",
stmt="""list(dropwhile(lambda x: x == 0, l))""") #2.308
print timeit.timeit(
setup= """from collections import deque
l = [0, 0, 1, 1, 2, 2, 0]
def noLeadingZero(l):
d = deque(l)
for e in l:
if e == 0:
d.popleft()
else:
break
return list(d)""",
stmt="""noLeadingZero(l)""") #1.684 -> Win!
l = ['10000', '000001']
map(lambda x: x.strip('0'), l)
>>> ['1', '1']
I'm guessing your lists contains strings of the integers? 我猜你的列表包含整数的字符串? Like
['001','100']
as opposed to [001,100]
? 像
['001','100']
而不是[001,100]
?
Try [x.strip('0') for x in bigList]
. [x.strip('0') for x in bigList]
尝试[x.strip('0') for x in bigList]
。 See str.split
in python docs . 请参阅python docs中的
str.split
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.