python信息去重练习
时间: 2023-10-03 19:07:24 浏览: 82
可以使用set()函数来去重,例如:
```python
original_list = [1, 2, 3, 2, 4, 1, 5]
new_list = list(set(original_list))
print(new_list)
```
输出结果为:[1, 2, 3, 4, 5]
如果需要保持原有顺序,可以使用OrderedDict:
```python
from collections import OrderedDict
original_list = [1, 2, 3, 2, 4, 1, 5]
new_list = list(OrderedDict.fromkeys(original_list))
print(new_list)
```
输出结果为:[1, 2, 3, 4, 5]
相关问题
python列表去重练习题
Python中去除列表重复元素可以通过多种方法实现,这里提供几个常见的例子:
1. **使用set**:由于集合(Set)不允许有重复元素,可以先将列表转换为集合,然后再转回列表。
```python
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(set(lst))
```
2. **使用列表推导式**:
```python
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = [x for i, x in enumerate(lst) if lst.index(x) == i]
```
3. **使用字典**(如果列表元素可哈希):
```python
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(dict.fromkeys(lst))
```
4. **传统循环**:
```python
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = []
for item in lst:
if item not in unique_lst:
unique_lst.append(item)
```
python数据类型练习
以下是Python数据类型练习的一些例子:
1. 将字符串转换为数字
```python
a = "123"
print(type(a)) # 输出:<class 'str'>
b = int(a)
print(type(b)) # 输出:<class 'int'>
```
2. 判断字典中是否存在某个值
```python
dic = {"key01": "value01", "key02": "value02", "key03": "value03"}
v1 = "key01" in dic.keys()
v2 = "value01" in dic.values()
print(v1) # 输出:True
print(v2) # 输出:True
```
3. 列表切片
```python
lst = [1, 2, 3, 4, 5]
print(lst[1:3]) # 输出:[2, 3]
```
4. 列表去重
```python
lst = [1, 2, 3, 2, 4, 3, 5]
lst = list(set(lst))
print(lst) # 输出:[1, 2, 3, 4, 5]
```
5. 列表排序
```python
lst = [3, 1, 4, 2, 5]
lst.sort()
print(lst) # 输出:[1, 2, 3, 4, 5]
```
6. 判断变量类型
```python
a = None
b = ""
c = ()
d = []
e = {}
f = 0
print(bool(a)) # 输出:False
print(bool(b)) # 输出:False
print(bool(c)) # 输出:False
print(bool(d)) # 输出:False
print(bool(e)) # 输出:False
print(bool(f)) # 输出:False
```
阅读全文