python set()函数
时间: 2023-08-21 07:05:19 浏览: 41
set()函数是Python中的一个内置函数,用于创建一个集合(set)对象。它可以接受一个可迭代对象作为参数,例如列表、元组、字符串等,然后将其中的元素去重后放入一个新的集合中。
set()函数的语法如下:
set(iterable)
其中,iterable表示一个可迭代对象,例如列表、元组、字符串等。
使用set()函数可以快速去重,例如:
>>> a = [1, 2, 3, 2, 1]
>>> b = set(a)
>>> print(b)
{1, 2, 3}
此外,set()函数还可以用于集合的运算,例如求交集、并集、差集等。
相关问题
Pythonset函数
Python中的set函数是用来创建一个无序且不重复的集合。可以使用set()函数来创建一个空集合,也可以使用花括号{}来创建一个非空集合。set函数可以接受一个可迭代对象作为参数,例如列表、元组、字符串等。
以下是两个关于set函数的例子:
1. 创建一个空集合:
```python
empty_set = set()
print(empty_set) # 输出:set()
```
2. 创建一个非空集合:
```python
fruits = {'apple', 'banana', 'orange'}
print(fruits) # 输出:{'banana', 'orange', 'apple'}
```
pythonset函数
Python中的set()函数用于创建一个无序且不重复的集合。你可以通过将其他可迭代对象(如列表、元组和字符串)作为参数传递给set()函数来创建集合。下面是一些关于set()函数的例子:
1. 将列表转换为集合:
```python
list1 = [1, 2, 3, 4, 5]
set1 = set(list1)
print(set1) # 输出:{1, 2, 3, 4, 5}
```
2. 将元组转换为集合:
```python
tuple1 = (1, 2, 3, 4, 5)
set2 = set(tuple1)
print(set2) # 输出:{1, 2, 3, 4, 5}
```
3. 将字符串转换为集合:
```python
str1 = "Hello, world!"
set3 = set(str1)
print(set3) # 输出:{'d', 'H', 'o', ',', 'l', 'e', '!', 'r', 'w', ' '}
```
这些例子展示了如何使用set()函数将不同类型的可迭代对象转换为集合。set()函数会自动去除重复的元素,并且集合中的元素是无序的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)