简体   繁体   English

如何在不使用 for 循环的情况下检查列表中的元素?

[英]How to check elements in a list WITHOUT using for loops?

Apologies if the title of the question is phrased badly.如果问题的标题措辞不当,请致歉。 I am currently trying to make a function that takes in a list of integers from 1 to n, where n is the length of the list.我目前正在尝试制作一个 function ,它接收从 1 到 n 的整数列表,其中 n 是列表的长度。 The function should return the first value that is repeated in the list. function 应返回列表中重复的第一个值 Duplicates are NOT always next to one another.重复项并不总是彼此相邻。 If one or more integers is less than 1 or if it is not a list, the function should return -1.如果一个或多个整数小于 1 或不是列表,则 function 应返回 -1。 If there are no duplicates, return 0.如果没有重复,则返回 0。

This is my current code:这是我当前的代码:

def find_duplicates(ls):
    if type(ls) != list:
        return -1

    non_dupe = []
    i = 0
    while i < len(ls):
        if ls[i] < 1:
            return -1
            break
        if ls.count(i) > 1:
            return i
            break
        else:
            non_dupe.append(i)
            i += 1

    if len(non_dupe) == len(ls):
        return 0

While this code works for a majority of test cases, it doesn't seem to pass虽然此代码适用于大多数测试用例,但它似乎没有通过

print(find_duplicates([1, 2, 2, 0]))

as it returns 2 instead of the expected -1.因为它返回 2 而不是预期的 -1。 I am relatively new to Python and I can't seem to be able to fix this error.我对 Python 比较陌生,我似乎无法修复此错误。 I've tried searching for ways to counter this problem but I am not allowed to use for loops to check through a list.我已经尝试寻找解决此问题的方法,但我不允许使用 for 循环来检查列表。 Any help is greatly appreciated.任何帮助是极大的赞赏。

EDIT: I am not allowed to use any of the following but anything else is accepted.编辑:我不允许使用以下任何内容,但可以接受其他任何内容。

  1. for loops for 循环
  2. min() / max()最小()/最大()
  3. enumerate() / zip ()枚举()/ zip()
  4. sort()种类()
  5. negative indexing eg ls[-1]负索引,例如 ls[-1]
  6. list slicing列表切片

Problem is beacause you are breaking while loop when find a duplicated.问题是因为您在找到重复项时打破了 while 循环。 In that case, function is finding first the duplicated.在这种情况下,function 首先找到重复项。

Try this:尝试这个:

def find_duplicates(ls):
    if type(ls) is not list:
        return -1
    duplicated = 0
    i = 0
    while i < len(ls):
        if ls[i] < 1:
            return -1
        if ls.count(ls[i]) > 1 and duplicated == 0
            duplicated = ls[i]
        i += 1
    return duplicated

Your test case returns 2 because 2 stay at lower indexes comparing to 0 .您的测试用例返回 2 因为20相比保持较低的索引。

I would suggest to sort the list before moving on:我建议在继续之前对列表进行sort

def find_duplicates(ls):
    if type(ls) != list:
        return -1

    sorted_list = ls.sorted()           #Assign sorted `ls` to another variable, while keeping the order of `ls` intact
    non_dupe = []
    i = 0
    
    while i < len(ls):
        if ls[i] < 1:
            return -1
            break
        if ls.count(i) > 1:
            return i
            break
        else:
            non_dupe.append(i)
            i += 1
    
    if len(non_dupe) == len(ls):
        return 0

Another method I would recommend is using set - a built-in data type of Python.我推荐的另一种方法是使用set - Python 的内置数据类型。 Maybe you should consider trying this approach later on when all test cases are passed.也许你应该考虑在所有测试用例都通过后尝试这种方法。 Have a look at this Tutorial for set usage: https://www.w3schools.com/python/python_sets.asp .查看本教程以了解set用法: https://www.w3schools.com/python/python_sets.asp

Your code returns a duplicate prematurely ;您的代码过早地返回重复项; traversing the list, the function first finds 2 as a duplicate, return it, and halts the function immediately.遍历列表,function 首先找到2作为重复项,将其返回,然后立即停止 function。 But it has not seen the 0 at the end.但它没有看到最后的0

So, you need to let the function see the list all the way towards the end, looking for a negative number.因此,您需要让 function 一直看到列表,寻找负数。 If a negative number is found along the way, you can halt the function.如果在途中发现负数,您可以停止 function。 If it does not see a negative number until the end, then let it return the duplicate value:如果它直到最后都没有看到负数,则让它返回重复值:

def find_duplicates(ls):
    if not isinstance(ls, list): # check whether ls is a list
        return -1

    dup = 0
    seen = [] # list of numbers seen so far
    i = 0 # index

    while i < len(ls):
        if ls[i] < 1: # if a negative number is found, return -1
            return -1
        if ls[i] in seen and dup == 0:
            dup = ls[i]
        seen.append(ls[i])
        i += 1
    return dup

print(find_duplicates([1, 2, 2, 0])) # -1
print(find_duplicates([1, 1, 2, 2, 3])) # 1

You were very close.你非常亲近。 Try this:尝试这个:

def find_duplicates(ls):
    if type(ls) != list:
        return -1   
    non_dupe = []
    i = 0
    while i < len(ls):
        if ls[i] < 1:
            return -1
        elif ls[i] in non_dupe:
            return ls[i]
        else:
            non_dupe.append(i)
        i += 1
    return 0
my_list = [1,2,2,0]

result = list(set(filter(lambda x: my_list.count(x) > 1 , my_list)))

# Result =>  [2]

I hope this solves your problem我希望这能解决你的问题

暂无
暂无

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

相关问题 如何比较两个具有相似元素的不同列表并使用循环创建没有相似元素的新列表 - How to compare two different lists with similar elements and create a new list without the similar elements using loops 如何根据python中的另一个列表删除列表中的元素,没有循环? - How to remove elements in a list based on another list in python, without loops? Python - 没有循环的列表元素乘法 - Python - list elements multiplication without loops 如何在不使用多个循环的情况下检查单词是否在字符串中 - How to check if a word is in a string without using multiple loops 如何使用python中的for循环计算列表中四个相邻元素的数量? - How to count the number of four adjecent elements in a list using for loops in python? 如何在不使用Python范围的情况下创建列表(对于循环)? - How to create a list without using range in Python (For Loops)? 如何在不使用循环的情况下计算python列表中的所有项目 - How to count all the items in the python list without using loops 如何在不使用循环的情况下在python中的列表中找到最大值 - How to finding maximum values in list in python without using loops 在不使用 for 或 while 循环的情况下将列表元素与 integer 进行比较(老师希望我们使用 reduce nd map) - Comparing elements of a list to an integer without using for or while loops (teacher wants us to use reduce nd map) 使用循环将数组列表中的元素乘以向量 - multiply elements in array list by vector using loops
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM