温馨提示×

Python中set函数去重的方法是什么

小亿
83
2024-05-13 18:38:14
栏目: 编程语言

在Python中,可以使用set()函数来去除列表、元组、字符串等数据结构中的重复元素。例如:

# 去除列表中的重复元素
my_list = [1, 2, 3, 1, 2, 3]
unique_list = list(set(my_list))
print(unique_list)

# 去除元组中的重复元素
my_tuple = (1, 2, 3, 1, 2, 3)
unique_tuple = tuple(set(my_tuple))
print(unique_tuple)

# 去除字符串中的重复字符
my_string = "hello"
unique_string = ''.join(set(my_string))
print(unique_string)

运行上述代码,将会输出去重后的列表、元组和字符串。

0