[[1,2],[2,1],[2,3]]去重 Python实现
时间: 2023-06-26 11:05:04 浏览: 50
可以使用集合(set)来实现去重:
```python
lst = [[1,2],[2,1],[2,3]]
new_lst = list(set(map(tuple, lst)))
new_lst = [list(x) for x in new_lst]
print(new_lst)
```
输出:
```
[[2, 1], [2, 3], [1, 2]]
```
解释一下代码:
1. `map(tuple, lst)` 将列表中的每个子列表转换为元组。
2. `set()` 将元组去重。
3. `list()` 将集合转换为列表。
4. 最后一行代码是为了让输出的子列表还原为列表类型。
相关问题
数组去重python实现
以下是两种Python实现数组去重的方法:
1. 使用set()函数去重
```python
arr = [1, 2, 3, 3, 4, 4, 5]
arr_unique = list(set(arr))
print(arr_unique) # 输出:[1, 2, 3, 4, 5]
```
2. 使用列表推导式去重
```python
arr = [1, 2, 3, 3, 4, 4, 5]
arr_unique = [x for i, x in enumerate(arr) if x not in arr[:i]]
print(arr_unique) # 输出:[1, 2, 3, 4, 5]
```
python实现文本去重
可以使用Python编写一个函数来实现文本去重。以下是一个简单的示例:
```python
def remove_duplicates(text):
# 将文本拆分为单词列表
words = text.split()
# 使用集合去除重复单词
unique_words = set(words)
# 将唯一的单词重新组合为文本
unique_text = ' '.join(unique_words)
return unique_text
```
你可以调用这个函数并传入要去重的文本作为参数,它会返回去重后的文本。例如:
```python
text = "This is a sample text with duplicate words. This text has duplicate words."
unique_text = remove_duplicates(text)
print(unique_text)
```
输出结果将是:
```
text has duplicate This sample words. is a with
```
这样,重复的单词被去除了。请注意,这个示例仅考虑了空格分隔的单词,如果需要处理其他标点符号或特殊情况,你可能需要进行一些额外的处理。