我有一堆包含整数的大列表。这些列表可能以几个零开头或结尾。
是否有一种简单的方法可以从列表的左侧或右侧剥离零?
类似于字符串的 lstrip()
或 rstrip()
的东西?
数据看起来像:
[0,0,0,1,2,3,4]
或者
[1,2,3,4,0,0,0]
我必须能够单独使用 lstrip()
或 rstrip()
。我不需要从列表的两侧都删除空格。
itertools.dropwhile()
函数:>>> L = [0, 0, 1, 1, 2, 2, 0]
>>> list(itertools.dropwhile(lambda x: x == 0, L))
[1, 1, 2, 2, 0]
与内置的itertools.dropwhile()
相比,有一种更有效率的解决方案。您可以使用全能的collections.deque
,它将是此任务的理想数据结构,因为其左侧或右侧的pop
是O(1)
。下面是左侧删除的情况,右侧删除将是其镜像:
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]
让我们测试其性能,与利用内置的itertools.dropwhile()
函数的以下代码进行比较:
from itertools import dropwhile
print(list(dropwhile(lambda x: x == 0, l)))
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']
我猜你的列表包含整数的字符串?像 ['001','100']
而不是 [001,100]
?
尝试使用 [x.strip('0') for x in bigList]
。请参阅 Python文档 中的 str.split
。
lstrip
和rstrip
函数。 - mathematical.coffee
rstrip()
变体:reversed(itertools.dropwhile(lambda x: x == 0, reversed(L)))
的翻译是:反转列表 L 并从末尾开始删除连续为零的元素,直到遇到第一个非零元素。 - user2665694list(reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(L)))))
。 - josch