我有一个清单,例如:
my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]
我只需要从内部列表中删除前导零和尾随零,以便最终得到:
new_list = [[1,2,2,1], [1,2], [1,2], [1,0,0,1]]
非常感谢任何帮助。
for sub_list in my_list:
for dx in (0, -1):
while sub_list and sub_list[dx] == 0:
sub_list.pop(dx)
my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]
my_list =[np.trim_zeros(np.array(a)) for a in my_list]
>>> my_list
[array([1, 2, 2, 1]), array([1, 2]), array([1, 2]), array([1, 0, 0, 1])]
如果你想要 numpy.
也可以这样做:
>>> my_list =[np.trim_zeros(a) for a in my_list]
>>> my_list
[[1, 2, 2, 1], [1, 2], [1, 2], [1, 0, 0, 1]]
一些时间安排:
Numpy
>>> timeit.timeit('my_list =[np.trim_zeros(a) for a in my_list]',setup='import numpy as np; my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]', number=10000)
0.08429217338562012
Numpy w/convert array
>>> timeit.timeit('my_list =[np.trim_zeros(np.array(a)) for a in my_list]',setup='import numpy as np; my_list = [[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,1]]', number=10000)
0.6929900646209717
所以最好不要在 np.array 进行转换,除非你以后要使用那种类型。
new_list = [map(int,"".join(map(str,x)).strip("0")) for x in my_list]
可能有用
>>> new_list = [map(int,"".join(map(str,x)).strip("0")) for x in my_list]
>>> new_list
[[1, 2, 2, 1], [1, 2], [1, 2], [1, 0, 0, 1]]
使用单个列表推导,并通过过滤生成器推导进行切片:
new_list = [l[next((i for i, n in enumerate(l) if n != 0), 0):
next((len(l) - i for i, n in enumerate(reversed(l)) if n != 0), 0)]
for l in my_list]
使用regex
和itertools.chain()
:
In [91]: my_lis=[[1,2,2,1], [0,0,1,2], [1,2,0,0], [1,0,0,10]]
In [92]: my_lis1=[[y.split() for y in filter(None,re.split(r"\b\s?0\s?\b",
" ".join(map(str,x))))] for x in my_lis]
In [93]: [map(int,chain(*x)) for x in my_lis1]
Out[93]: [[1, 2, 2, 1], [1, 2], [1, 2], [1, 10]]