Python:列表操作

时间:2011-06-23 15:34:59

标签: python list

我是100%的python新手,我知道我需要阅读更多,但我现在需要完成这项任务,这就是我使用python的原因。这是我的代码:

outputList = []

for line in open('cron.log', 'r'):
   m = line[45:47]
   outputList.append(m)

所以我打开文件,读取行,然后将我需要的2个字符追加到列表中。现在,我想从end(或列表的beginning开始,将该位置的elementelementbefore(或{ {1}})它。我怎样才能做到这一点?在C ++中,我会使用behinditerrator等进行front(),但我对python一无所知:(

3 个答案:

答案 0 :(得分:2)

#This is from the beginning
for i in range(1, len(outputList)):
    # == could be what ever comparison you want.  Any one in particular?
    if outputList[i] == outputList[i-1]:
        #do whatever you need to do

答案 1 :(得分:0)

你也可以使用这样的东西:

a = [1, 2, 3, 4, 5, 6, 7, 8]
# proceed backward
for x,y in ((a[i],a[i-1]) for i in xrange(len(a)-1,0,-1)):
    if x!= y:
        # do something

答案 2 :(得分:0)

outputList = [line[45:47] for line in open('cron.log', 'r')]

for idx, item in enumerate(outputList[:-1]):
    if item == outputList[idx+1]:
        # do something