Python中的拆分整数列表

时间:2014-04-09 18:52:43

标签: python

我有一个整数列表。我想将主列表拆分为多个非零整数子列表。

示例:

main_lists = [0,0,0,0,0,0,123,432,5,54,0,654,645,34,23,12,0,0,0,0,0,0,123,1,312,312,132,3,123,0,0,0,0,0,0,0]

output = 

[123,432,5,54,0,654,645,34,23,12]
[123,1,312,312,132,3,123]

条件是, 如果在两个非零值之间找到一个或两个(小于< 5)零,那么它应该包括那些零输出列表。如果找到超过5个连续零,那么它应该从该位置拆分列表。

main_lists = [0,0,0,0,0,0,123,432,5,54,0,654,645,34,23,12,0,0,0,0,0,0,123,1,312,312,132,3,123,0,0,0,0,0,0,0]
zero_count = 0
non_zero_temp = []
for i in main_lists:
    if i == 0:
        zero_count = zero_count + 1
    else:
        if zero_count < 5:
            non_zero_temp.append(i)
            zero_count = 0

先谢谢,

2 个答案:

答案 0 :(得分:1)

from itertools import groupby

main_lists = [
    0,0,0,0,0,0,123,432,5,54,0,654,645,34,23,12,0,
    0,0,0,0,0,123,1,312,312,132,3,123,0,0,0,0,0,0,0
]

# group numbers into contiguous lists (by 0 or not-0)
is_zero = lambda n: not n
groups = (list(nums) for zero,nums in groupby(main_lists, key=is_zero))

# group lists into contiguous chunks (by to-keep or to-discard)
is_keeper = lambda lst: bool(lst[0]) or len(lst) < 5
chunks = (chunk for keep,chunk in groupby(grouped, key=is_keeper) if keep)

# reassemble chunks
final = [[i for lst in chunk for i in lst] for chunk in chunks]

结果

[[123, 432, 5, 54, 0, 654, 645, 34, 23, 12], [123, 1, 312, 312, 132, 3, 123]]

答案 1 :(得分:1)

我会发布一个替代方案:

output = []
non_zero_temp = []
length = len(main_lists)
i = 0
while i < length:
    zeros = []
    while i < length and main_lists[i] == 0:
        i += 1
        zeros.append(0)
    if len(zeros) != 0 and len(zeros) < 5:
        non_zero_temp += zeros
    elif len(zeros) > 5:
        if len(non_zero_temp) > 0 and i < length:
            output.append(non_zero_temp)
            non_zero_temp = []
    else:
        non_zero_temp.append(main_lists[i])
        i += 1
if len(non_zero_temp) > 0:
    output.append(non_zero_temp)
print(output)

[[123, 432, 5, 54, 0, 654, 645, 34, 23, 12], [123, 1, 312, 312, 132, 3, 123]]