for循环错过了第一次迭代

时间:2019-05-04 19:36:46

标签: python list

#!/usr/bin/env python

new_trace=[1,2,2,3,2,1,4,3,2,1,3,4,3,5,6,4,7,6,5,4,5,4,6,6,5,6,4,4,5,6,7,7,6,5,5,7,6,5]

def extractIntervals(new_trace):
    listofAppearances=[[new_trace[0]],[0],[-1]]
    for i in range(0,len(new_trace)-1,1):
        if new_trace[i] in listofAppearances[0]:
            continue
        else:
            listofAppearances[0].append(new_trace[i])
            listofAppearances[1].append(i)
            listofAppearances[2].append(-1)
    print(listofAppearances)

    for j in range(len(new_trace)-1,0,-1):
        for k in range(0,len(listofAppearances[0])-1,1):
            if (new_trace[j]==listofAppearances[0][k]) and (listofAppearances[2][k]==-1):
                listofAppearances[2][k]=j
            else:
                continue

    print(listofAppearances)

def main():
    extractLivenessIntervals(new_trace)

if __name__ == "__main__":
        main()

在上面的代码中,我试图提取外观间隔(由列表中每个数字的第一个和最后一个外观索引分隔),我的方式是对列表进行一次解析,如果该数字仍然不存在在 listOfAppearances 中,然后将其附加到第一列,将索引附加到第二列,并将第三列设置为 -1

我再次反解析每个元素的列表,然后在 listofappearances 中查找,如果仍设置为-1,则对应的第三列更改为当前索引。

这可行,但是向后解析列表时的第一次迭代存在一些我无法解决的问题。这个清单范例的结果是:

[[1, 2, 3, 4, 5, 6, 7], [0, 1, 3, 6, 13, 14, 16], [-1, -1, -1, -1, -1, -1, -1]]
[[1, 2, 3, 4, 5, 6, 7], [0, 1, 3, 6, 13, 14, 16], [9, 8, 12, 27, 37, 36, -1]]

您可以看到第二个列表的最后一个元素仍然设置为-1,我不明白为什么!我检查了代码的每一寸,我看不出为什么会这样!

2 个答案:

答案 0 :(得分:1)

只是改变

for k in range(0, len(listofAppearances[0])-1, 1):

for k in range(0, len(listofAppearances[0]), 1):

在第17行。


编辑:,您可以通过以下方式获得相同的结果:

def extractIntervals(new_trace):
    listofAppearances = [0, 0, 0]
    listofAppearances[0] = list(set(new_trace))
    # returns new_trace without repeated elements

    listofAppearances[1] = [new_trace.index(i) for i in list(set(new_trace))]
    # returns a list with the index of the first occurrence
    # in new_trace of each element in list(set(new_trace))

    listofAppearances[2] = [len(new_trace) - 1 - new_trace[::-1].index(i) for i in list(set(new_trace))]
    # returns a list with the index of the last occurrence
    # in new_trace of each element in list(set(new_trace))

    print(listofAppearances)

答案 1 :(得分:0)

我建议处理值流吗?首先定义一些辅助函数,然后使用它们将每个元素与出现它的位置分组。

from itertools import groupby
from operator import itemgetter


second = itemgetter(1)
first_and_last = itemgetter(0, -1)


def sort_and_group(seq, k):
    return groupby(sorted(seq, key=k), k)


def extract_intervals(new_trace):
    tmp1 = sort_and_group(enumerate(new_trace), second)
    tmp2 = [(val, *first_and_last([x for x,_ in positions])) for val, positions in tmp1]
    return zip(*tmp2)


new_trace=[1,2,2,3,2,1,4,3,2,1,3,4,3,5,6,4,7,6,5,4,5,4,6,6,5,6,4,4,5,6,7,7,6,5,5,7,6,5]

print(list(extract_intervals(new_trace)))

tmp1是每个元素与它发生位置的列表的配对。

tmp2是一个三元组列表,由一个列表元素以及它出现的第一个和最后一个位置组成。

zip的调用将三元组列表“解压缩”为三个元组:元素,第一个位置和最后一个位置。

相关问题