简体   繁体   English

比较列表的所有元素

[英]Compare all elements of a list

To illustrate my problem, imagine I have a list and I want to compare each element with the next one to check if they are the same value.为了说明我的问题,假设我有一个list ,我想将每个元素与下一个元素进行比较,以检查它们是否是相同的值。 The problem is that when I try to access the last element of the list and compare it with "the next one", that one is out of range, so I would get an error.问题是,当我尝试访问列表的最后一个元素并将其与“下一个”进行比较时,该元素超出了范围,因此会出现错误。 So, to avoid this, I put a condition when accessing that last element, so I avoid the comparison.所以,为了避免这种情况,我在访问最后一个元素时设置了一个条件,所以我避免了比较。

list = [1, 2, 1, 1, 5, 6, 1,1]

for i in range(len(list)):
    if i == len(list)-1:
        print('Last element. Avoid comparison'')
    else:
        if list[i] == list[i+1]:
            print('Repeated')

I guess that there should be a more efficient way to do this.我想应该有一种更有效的方法来做到这一点。 For instance, I was trying to set the condition in the definition of the for loop, something like this:例如,我试图在 for 循环的定义中设置条件,如下所示:

for i in range(len(list)) and i < len(list)-1

But that is invalid.但这是无效的。 Any suggestion about how to do this in a more efficient/elegant way?关于如何以更有效/优雅的方式做到这一点的任何建议?

You can utilize the functionality of range as follows:您可以使用 range 的功能,如下所示:

for i in range(1, len(list):
    if list[i-1] == list[i]:
        print('Repeated')

In this way, you won't overrun the list.这样,您就不会超出列表。

If you need to start from 0, you should use:如果你需要从 0 开始,你应该使用:

for i in range(len(list) - 1):
    if list[i] == list[i + 1]:
        print('Repeated')

The parameter stop of range function is just integer, so you can use value len(list) - 1 instead of len(list) to stop iterating on last but one element. 范围function 的参数stop只是 integer,因此您可以使用值len(list) - 1而不是len(list)来停止对最后一个元素的迭代。

start from one and look backwards从一开始向后看

for i in range(1, len(list)): 
    if list[i-1] == list[i]:
        print('Repeated')

This works!这行得通!

list = [1, 2, 1, 1, 5, 6, 1, 1]

for i in range(len(list)):    
    if i+1 < len(list) and list[i] == list[i+1]:
        print('Repeated')
  • len(list) is 8长度(列表)为 8
  • range(len(list)) is 0, 1, ..., 7 but you want the for loop to skip when the index is 6 right? range(len(list)) 为 0, 1, ..., 7 但您希望在索引为 6 时跳过 for 循环,对吗?

so given that case... if i == len(list)-1: this condition will be True when the index is 7 (not the index that you want)所以在这种情况下...... if i == len(list)-1:当索引为 7 时,此条件将为真(不是您想要的索引)

Just change that to if i == len(list)-2:只需将其更改为if i == len(list)-2:

Other answers have solved this, but I think it's worth mentioning an approach that may be closer to idiomatic Python.其他答案已经解决了这个问题,但我认为值得一提的方法可能更接近惯用的 Python。 Python provides iterable unpacking and other tools like the zip function to avoid accessing elements of sequences by index. Python 提供可迭代解包和其他工具,如zip function 以避免通过索引访问序列元素。

# Better to avoid shadowing the build-in name `list`
a_list = [1, 2, 1, 1, 5, 6, 1, 1]

for value, following_value in zip(a_list, a_list[1:]):
    if value == following_value:
       print("Repeated!")

There are many ways to do this.有很多方法可以做到这一点。 The most common one is to use zip to pair each item with its successor:最常见的是使用 zip 将每个项目与其后继项目配对:

if any(item == successor for item,successor in zip(lst,lst[1:])):
    print('repeated')

groupby from itertools is also a popular choice (but not optimal for this):来自 itertools 的groupby也是一个流行的选择(但不是最佳选择):

if any(duplicate for _,(_,*duplicate) in itertools.groupby(lst)):
    print('repeated')

A for-loop would only need to track the previous value (no need for indexing): for 循环只需要跟踪前一个值(不需要索引):

prev = object() # non-matching initial value
for x in lst:
    if prev==x:              # compare to previous
       print('repeated')
       break
    prev = x                 # track previous for next iteration

Iterators can be interesting when traversing data in parallel (here the elements and their predecessors):并行遍历数据时,迭代器可能会很有趣(这里是元素及其前身):

predecessor = iter(lst)         # iterate over items from first
for x in lst[1:]:               # iterate from 2nd item
    if x == next(predecessor):  # compare to corresponding predecessor
        print('repeated')
        break
list = [1, 2, 1, 1, 5, 6, 1,1]

for i in range(len(list)):
    if list[i] in list[i+1:i+2]:
        print('repeated')

If you use only numbers in your list, you might want to work with numpy for instance:如果您只使用列表中的数字,您可能希望使用numpy例如:

import numpy as np
np_arr = np.array(lst)  # don't use 'list' for your object name. 
diffs = np.diff(np_arr)
diffs_indices = np.where(diffs != 0)[0]

It is unclear what your exact uses, but for example in my code, you will get:目前尚不清楚您的确切用途,但例如在我的代码中,您将获得:

>>> diffs_indexes
array([0, 1, 3, 4, 5])

Which are the indices where elelment[i] != element[i+1]哪些是元素 [i] != element[i+1] 的索引

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

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