如何将列表拆分为一行6个零和其他值的子列表



这是我的列表:

a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]

我想将列表分成一行6个零和其他值的子列表,以获得所需的

输出
a = [[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]

我尝试将列表转换为字符串以使用拆分函数,然后将字符串转换回列表

b = ''.join(map(str,a))
c = b.split('0'*6)
d = list(map(int, c))

和int()以10为基数的无效文字结束:"错误消息。

这样做对吗?或者有一种不同的方式,不涉及列表和字符串之间的切换,以避免这样的错误消息?

下面是一种相当粗糙的方法:

a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]
output, temp = [], []
while a:
if a[:6] == [0] * 6:
if temp:
output.append(temp)
temp = []
output.append([0] * 6)
a = a[6:]
else:
temp.append(a[0])
a = a[1:]
else:
if temp:
output.append(temp)
print(output)
# [[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]

这将耗尽原始列表a

这样做的一种方法是创建一个生成器来跟踪到目前为止看到的0和数字。当你得到6个0时,你放弃它和之前的任何数字。否则将零移到另一个列表。

a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]
def six_zeros(l):
z = []
nums = []
for n in l:
if n != 0:
nums.extend(z)    # add zeros seen so far
nums.append(n)    # append the number
z = []
else:
z.append(n)       # append the zero
if len(z) == 6:   # but you've seen 6 yield them
if nums:
yield nums
yield z
nums = []
z = []
if nums or z:              # don't forget any left-overs
nums.extend(z)
yield nums
list(six_zeros(a))
# [[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]

我想这可能是一个更简单的方法:

a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]
six_zeros = [0]*6
b, temp = [], []
for x in a:
temp.append(x)
temp_len = len(temp)
if temp_len >= 6 and temp[-6:] == six_zeros:
if temp_len > 6:
b.append(temp[:-6])
b.append(six_zeros)
temp.clear()
if temp:
b.append(temp)
print(b)

输出:

[[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]

这是你的尝试的工作版本:

import re
a = [0, 0, 0, 0, 0, 0, 1, 1, 4, 5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 3, 4]
b = ''.join(map(str, a))
c = re.split(f"({'0'*6})", b)
d = [list(map(int, g)) for g in c if g]
print(d)

输出:

[[0, 0, 0, 0, 0, 0], [1, 1, 4, 5, 0, 0, 4], [0, 0, 0, 0, 0, 0], [1, 3, 4]]

我使用re.split,因为当被要求时,它包含分隔符。

最新更新