Python 从给定列表中找出只出现一次的数
时间: 2024-05-08 13:22:19 浏览: 61
可以使用 Python 中的 Counter 类来统计列表中每个元素出现的次数,然后再遍历一次列表找到只出现一次的数。
示例代码如下:
```python
from collections import Counter
def find_unique(nums):
count = Counter(nums)
for num in nums:
if count[num] == 1:
return num
return None
```
其中,`Counter(nums)` 将列表转换成一个字典,键为列表中的元素,值为该元素出现的次数。然后遍历列表,如果该元素出现的次数为 1,就返回该元素。如果遍历完列表都没有找到只出现一次的数,就返回 `None`。
相关问题
从给定列表中找出只出现一次的数
这个问题可以使用哈希表来解决。我们可以遍历列表,将每个数字作为键存储在哈希表中,值为该数字出现的次数。然后再遍历一次列表,找到值为1的键即可。
以下是示例代码:
```python
def find_unique(nums):
counts = {}
for num in nums:
if num in counts:
counts[num] += 1
else:
counts[num] = 1
for num in nums:
if counts[num] == 1:
return num
return None
```
如果列表中没有只出现一次的数,则返回 None。
py从给定列表中找出只出现一次的数
可以使用Python中的Counter库来实现:
```python
from collections import Counter
def find_unique(lst):
count = Counter(lst)
return [x for x in count if count[x] == 1]
```
其中,Counter(lst)会返回一个字典,记录了列表lst中每个元素出现的次数。接着,使用列表推导式[x for x in count if count[x] == 1],筛选出只出现一次的元素并返回。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)