简体   繁体   English

在 Python 中使用 enumerate() 访问下一个索引 (+1)

[英]Accessing next index (+1) using enumerate() in Python

First post here, so any protocol/style things please let me know.第一次在这里发帖,所以任何协议/风格的事情请告诉我。 I'm only about 2 mos into programming so still figuring out the ropes.我对编程只有大约 2 个月的时间,所以仍在弄清楚绳索。

I'm trying to take a string (ex.'AAAABBBCCDAABBB') and return only discrete occurrences of a character while preserving the original order.我正在尝试获取一个字符串(例如'AAAABBBCCDAABBB')并仅返回字符的离散出现,同时保留原始顺序。 If a letter repeats after another new letter has been introduced that is ok.如果一个字母在另一个新字母被引入后重复,那没关系。 So a successful return would be ['A', 'B', 'C', 'D', 'A', 'B'].所以成功的返回应该是 ['A', 'B', 'C', 'D', 'A', 'B']。

After many different ways, I'm trying to use enumerate() such as:经过许多不同的方式,我正在尝试使用 enumerate() 例如:

#If j doesn't match the j with an index of + 1, assign it to the list.

def unique_in_order(iterable):
    output= []
    for i, j in enumerate(iterable):
        if j != j[i + 1]:  #Pretty sure the issue is in this line
            output.append(j)
    return output
        

I'm not 100% on the syntax of accessing the index + 1 of j.我不是 100% 访问 j 的索引 + 1 的语法。 I'm also getting a string index out of range error here, which I'm assuming is when the iteration gets to the last j that means the next index is off the edge of the cliff and returns the error.我也在这里得到一个字符串索引超出范围错误,我假设是当迭代到达最后一个 j 时,这意味着下一个索引离开悬崖边缘并返回错误。 I haven't been able to find/generate a good solution to this.我一直无法找到/生成一个好的解决方案。 Something with len(j) I'm guessing but coming up short.我猜有 len(j) 的东西,但很短。

thanks!谢谢!

You could wrap everything in a try-catch block.您可以将所有内容都包装在 try-catch 块中。 If an IndexError exception is raised, we know we must have hit the end如果引发IndexError异常,我们知道我们一定已经结束了

def unique_in_order(iterable):
    output = []
    for index, element in enumerate(iterable):
        try:
            if element != iterable[index+1]:
                output.append(element)
        except IndexError:
            output.append(element)
            break
    return output

print(unique_in_order("AABCCCDDDDDEE"))

Output:输出:

['A', 'B', 'C', 'D', 'E']
>>> 

Or, like the comments suggest, just use itertools.groupby :或者,就像评论建议的那样,只需使用itertools.groupby

def unique_in_order(iterable):
    from itertools import groupby

    return [key for key, _ in groupby(iterable)]

print(unique_in_order("AABCCCDDDDDEE"))

Output:输出:

['A', 'B', 'C', 'D', 'E']
>>> 

You could just check that the last item in output is not the same as the current value您可以检查输出中的最后一项是否与当前值不同

def unique_in_order(iterable):
    output= []
    for j in iterable:
        # add to list if output empty
        #  or current value not equal to last value
        # in output
        if not output or j != output[-1]:
            output.append(j)
    return output

print(unique_in_order('AAAABBBCCDAABBB')) # ['A', 'B', 'C', 'D', 'A', 'B']

Or Correcting Posted Approach或纠正张贴的方法

Rather than this而不是这个

if j != j[i + 1]:  

You probably meant你可能是说

if i < len(iterable) -1 and j != iterable[i + 1]: 

But, this is still incorrect.但是,这仍然是不正确的。 It won't pick up the last B in the end group '...ABBB'它不会在结束组“...ABBB”中选择最后一个 B

Better更好的

def unique_in_order(iterable):
    output= []
    for i, j in enumerate(iterable):
        # On first index or
        # Adds first element of group
        # so even if group starts on last item in string
        # it still gets added
        if i == 0 or j != iterable[i-1]:
            output.append(j)
    return output

 print(unique_in_order('AAAABBBCCDAABBB')) # ['A', 'B', 'C', 'D', 'A', 'B']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM