如何将输出放在数组中?

问题描述 投票:-4回答:1

如何将生成的输出放在数组中?然后我想通过前面的元素减去每个元素。例如:6-0,7-6,10-7等获得运行长度。

for index, item in enumerate(binary_sequence):
    if item == 1:
        print(index)

输出:

6
7
10
11
15
16
19
30
35
44
48
49
51
54
55
56
57
60
74
76
78
80
85
90
97
98
python arrays list
1个回答
0
投票

Python有办法避免常见操作的索引

zip允许您配对列表并迭代配对值,将列表与其自身的偏移版本配对是常见的

seq = [*range(7, 30, 4)]

seq
Out[28]: [7, 11, 15, 19, 23, 27]

out = []
for a, b in zip(seq, [0] + seq):  # '[0] + seq' puts a '0' in front, shifts rest over
    out.append(a - b)

print(out)
[7, 4, 4, 4, 4, 4]
© www.soinside.com 2019 - 2024. All rights reserved.