如何删除重复项?

时间:05-09
要删除列表、数组或其他数据结构中的重复项,您可以使用多种编程语言。以下是三种不同语言的示例:
1. Python:
```python
def remove_duplicates(data):
unique_data = []
for item in data:
if item not in unique_data:
unique_data.append(item)
return unique_data

data = [1, 2, 3, 1, 5, 6, 7, 8, 9, 1]
unique_data = remove_duplicates(data)
print(unique_data)
# Output: [1, 2, 3, 5, 6, 7, 8, 9]
```
2. JavaScript (ES6 ):
```javascript
function removeDuplicates(data) {
const set = new Set();
const uniqueData = [];

for (const item of data) {
if (!set.has(item)) {
set.add(item);
uniqueData.push(item);
}
}

return uniqueData;
}

let data = [1, 2, 3, 1, 5, 6, 7, 8, 9, 1];
let uniqueData = removeDuplicates(data);
console.log(uniqueData);
// Output: [1, 2, 3, 5, 6, 7, 8, 9]
```
3. Java:
```scss
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class RemoveDuplicatesExample {
public static void main(String[] args) {
List data = List.of(1, 2, 3, 1, 5, 6, 7, 8, 9, 1);

// Create a HashSet to store the distinct items.
HashSet uniqueSet = new HashSet<>();

// Iterate over the list and add distinct elements to the HashSet.
for (int item : data) {
uniqueSet.add(item);
}

// Convert the HashSet back to a List of integers.
List uniqueData = new ArrayList<>(uniqueSet);
System.out.println(uniqueData);
}
// Output: [1, 2, 3, 5, 6, 7, 8, 9]
```
这些代码片段分别展示了如何使用Python、JavaScript和Java的不同方法来去除列表或数组中的重复值。请注意,对于大型数据集或使用特定算法实现时可能存在性能差异。
阅读:11次

分类栏目