PYTHON 数组去重
- User
PYTHON 数组去重
Assistant
Python中有几种常用的数组去重方法:
1. 使用 set() - 最简单快速
python# 对列表去重 arr = [1, 2, 2, 3, 4, 4, 5] unique_arr = list(set(arr)) print(unique_arr) # [1, 2, 3, 4, 5] # 注意:set会打乱原有顺序2. 保持原有顺序的去重
python# 方法1:使用dict.fromkeys() arr = [1, 2, 2, 3, 4, 4, 5] unique_arr = list(dict.fromkeys(arr)) print(unique_arr) # [1, 2, 3, 4, 5] # 方法2:手动遍历 arr = [1, 2, 2, 3, 4, 4, 5] unique_arr = [] for item in arr: if item not in unique_arr: unique_arr.append(item) print(unique_arr) # [1, 2, 3, 4, 5]
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.