列表上的选择性迭代

时间:2013-03-21 02:08:04

标签: python

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

[ '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']

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

  

//考虑2个变量a& b //

     

应该存储0-21之间的差异(避免应该是21-0)   负值)

然后

  

b应存储21-51之间的差异(应该是51-21到   避免负值)

然后再次

  

a应存储51-67之间的差异(应该是67-51到   避免负值)

然后

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

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

我完全没有关于如何继续这一步的想法。

3 个答案:

答案 0 :(得分:1)

您对问题的描述仍然不清楚,据我所知,这可能是您所寻找的:

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

答案 1 :(得分:1)

只要列表包含偶数个元素,这将起作用:

# original list
l = ['0', '21', '51', '67', '96', '102', '128', '130']

# convert items in list to integers
l = map(lambda x: int(x), l)

# split the list in two, even indices in p, odd indices in q
p = l[::2]
q = l[1::2]

# print out the calculations
for n in range(len(p)):
    print 'abs(%s - %s) = %s' % (p[n], q[n], abs(p[n]-q[n]))

它打印出来像这样:

abs(0 - 21) = 21
abs(51 - 67) = 16
abs(96 - 102) = 6
abs(128 - 130) = 2

如果您不知道上述代码中的切片副本,请查看以下内容:

>>> l[::2]
['0', '51', '96', '128']
>>> l[1::2]
['21', '67', '102', '130']

语法如此list_name[starting_point:ending_point:increment_by]

答案 2 :(得分: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]


li = [(int(li[i]),int(li[i+1])) for i in range( len( li ) - 1 ) if li[i+1] != '0']


for a, b in li:
    x = abs(a - b)
    print '|%3d - %3d| = %3d' % (a,b,x)