用Python 写一个列表去重
时间: 2023-05-22 14:00:53 浏览: 79
可以使用 set() 函数来去重一个列表,示例代码如下:
```python
my_list = [1, 2, 3, 2, 4, 1, 5, 3]
my_set = set(my_list)
new_list = list(my_set)
print(new_list)
```
输出结果为:
```
[1, 2, 3, 4, 5]
```
相关问题
用Python写一个列表去重的代码
好的,以下是Python写一个列表去重的代码:
``` python
old_list = [1, 2, 3, 4, 5, 4, 3, 2, 1]
new_list = list(set(old_list))
print(new_list)
```
这段代码将打印出[1, 2, 3, 4, 5],这是一个去重后的列表。
用python写一个文件去重
可以使用 Python 的 set 数据结构来去重文件中的行。
首先,打开文件并读取每一行,将每一行添加到 set 中。由于 set 中的元素是唯一的,因此会自动去重。然后,将 set 中的元素写回文件即可。
下面是一个示例代码:
```
# 打开文件
with open('input.txt', 'r') as f:
# 创建 set
lines = set()
# 读取每一行并添加到 set 中
for line in f:
lines.add(line)
# 将 set 中的元素写回文件
with open('output.txt', 'w') as f:
for line in lines:
f.write(line)
```
上述代码会读取 `input.txt` 文件中的所有行,并使用 set 去重后写回 `output.txt` 文件。