简体   繁体   English

如何在 Python 3 中定义一个函数来对数组进行排序并返回只存在一次而不是两次的数字

[英]how to define a function in Python 3 that sort an array and return the number that exists only once rather than twice

in this code I want to do the following 1- sort the array 2- Iterate over it to find an element that exists only once while every other element exist twice.在这段代码中,我想执行以下操作 1- 对数组进行排序 2- 迭代它以查找仅存在一次而其他每个元素都存在两次的元素。 e,g [2,1,3,2,3], answer is 1 3- In iteration I do the following ->If reached last element , then last element is the wanted ->If an element i is not equal to element i+1, then element i is the wanted 4- at the end return -1 if not found e,g [2,1,3,2,3], 答案是 1 3- 在迭代中,我执行以下操作 ->如果到达最后一个元素,则最后一个元素是想要的 ->如果元素 i 不等于元素i+1,然后元素 i 是想要的 4- 如果没有找到,最后返回 -1

this is my code, please help me, I am new in Python这是我的代码,请帮助我,我是 Python 新手

class Main:
    def singleNumber(self, nums: List[int]) -> int:
        sorted(nums)
        l =len(nums)
        while i<l:
            if i+1==l:
                re=nums(i)
            if nums(i)!=nums(i+1):
                re=nums(i)
            else:
                i+=1
            re=-1
        return re

you can use collections.Counter with the built-in function sorted :您可以使用带有内置函数sorted collections.Counter

from collections import Counter
nums = [2,1,3,2,3]


sorted(k for k, v in Counter(nums).items() if v == 1)

output:输出:

[1]

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

相关问题 Python:仅在包存在时定义函数 - Python: Define a function only if package exists 如何多次执行 function 并将其输出连接到仅在 python 中的数组中 - how to execute a function more than once and concatenate its outputs into an array only in python 如何为 Python 类而不是其实例定义运算符 - How to define an operator for a Python class, rather than its instances 是否建议在 python 函数中使用打印语句而不是返回 - Is it advisable to use print statements in a python function rather than return 如何将相同的参数两次或多次解析为python脚本? - How to parse same argument twice or more than once to python script? 如何调整 function 以初始化正文中的数组而不是 function 的参数? - How to adjust a function to initialise array in body rather than argument of function? python - 如何制作 function 来检查按钮是否按下了一次或两次? - python - how to make a function to check if button pressed once or twice? python方法返回字符串而不是instancemethod - python method return string rather than instancemethod Python:如何继承和显示类中定义的id,而不是非得在对象中定义 - Python: How to inherit and display the id defined in the class, rather than have to define it in the object 用于Python的模拟库,在模拟函数中仅返回一次值? - Mock library for Python, return value only once in mocked function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM