gpt4 book ai didi

python - 列表上的选择性迭代

转载 作者:行者123 更新时间:2023-12-01 05:47:45 25 4
gpt4 key购买 nike

我有一个巨大的列表,如下所示:

[ '0', '21', '51', '67', '96', '102', '128', '130', '0', '11', '36', '53', '81', '86', '113', 116', '0', '21', '48', '64', '91', '95','125', '139', '166', '175', '200', '205']

我必须对列表的元素进行简单的减法,这样:

//Consider 2 variables a & b//

a should store the difference between 0-21 (it should be 21-0 to avoid negative values)

然后

b should store the difference between 21-51 (it should be 51-21 to avoid negative values)

然后再说

a should store the difference between 51-67 (it should be 67-51 to avoid negative values)

然后

b = 67-96
a = 96-102
b = 102-128
a = 128-130

130 和后面的 0 之间不应有减法。新的迭代应该从 0-11,11-36 开始,依此类推,直到遇到下一个 0

我完全不知道如何继续这一步。

最佳答案

您对问题的描述仍然不清楚,据我了解,这可能就是您正在寻找的:

li = [ 0, '21', '51', '67', '96', '102', '128', '130', '0', '11', '36', '53', '81', '86', '113', '116', '0', '21', '48', '64', '91', '95','125', '139', '166', '175', '200', 205]   

# Convert all items to integers for calculations
li = [int(x) for x in li]

for x, y in zip(li, li[1:]):
if y != 0:
a = abs(x - y)
print '|%3d - %3d| = %3d' % (x, y, a)
else:
print ''

输出:

|  0 -  21| =  21
| 21 - 51| = 30
| 51 - 67| = 16
| 67 - 96| = 29
| 96 - 102| = 6
|102 - 128| = 26
|128 - 130| = 2

| 0 - 11| = 11
| 11 - 36| = 25
| 36 - 53| = 17
| 53 - 81| = 28
| 81 - 86| = 5
| 86 - 113| = 27
|113 - 116| = 3

| 0 - 21| = 21
| 21 - 48| = 27
| 48 - 64| = 16
| 64 - 91| = 27
| 91 - 95| = 4
| 95 - 125| = 30
|125 - 139| = 14
|139 - 166| = 27
|166 - 175| = 9
|175 - 200| = 25
|200 - 205| = 5

关于python - 列表上的选择性迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15538252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com