python用input输入集合
Python是一种非常强大和灵活的编程语言,非常受欢迎。一个好的Python程序需要处理输入和输出。一种输入数据的方式是使用input函数。在这篇文章中,我们将探讨如何使用Python的input函数来输入集合。
一、什么是集合
在Python中,集合是一组唯一且不可变的元素。集合是由大括号({})或set()函数创建的。通过添加和删除元素可以修改集合。集合还可以用于以下基本操作:联合,交集和差集。
例如,以下是创建和修改集合的示例:
```python
# 创建集合
fruit = {'apple', 'banana', 'orange'}
# 添加元素
fruit.add('pear')
# 删除元素
fruit.discard('banana')
```
二、使用input函数创建集合
在Python中,我们可以使用input函数获取用户输入的数据。以下是使用input函数创建集合的代码示例:
```python
# 从用户输入中创建集合
numbers = set(input("Enter a series of numbers separated by commas: ").split(','))
print(numbers)
```
在上面的示例中,我们使用input函数从用户输入中获取一系列用逗号分隔的数字,然后使用split函数将其拆分为单独的项。最后,我们使用set函数将这些项目转换为集合并打印输出。
需要注意的是,由于input函数返回的是一个字符串,所以我们需要使用split函数将其拆分为单独项,再使用set函数将这些项转换为集合。
三、输入集合中的元素类型
在input函数中输入集合时,由于输入的原始数据类型是字符串,所以最终集合中的元素类型也将是字符串。如果需要将集合中的元素转换为其他类型,可以使用以下方式:
1. 将字符串转换为数字
```python
numbers = set(map(int, input("Enter a series of numbers separated by commas: ").split(',')))
```
2. 将字符串转换为日期
```python
from datetime import datetime
dates = set(map(lambda x: datetime.strptime(x, '%m/%d/%Y'), input("Enter a series of dates separated by commas: ").split(',')))
```
以上两个示例分别演示了如何将集合中的字符串元素转换为数字类型和日期类型。
四、输入中包含重复元素
由于集合中的元素必须是唯一的,如果输入中包含重复元素,那么只有一个元素会添加到集合中。以下是一个示例:
```python
fruit = set(input("Enter a series of fruit separated by commas: ").split(','))
print(fruit)
```
如果输入了"apple, apple, orange, pear",那么只有"apple"会添加到集合中。输出结果:
```python
{'apple', 'pear', 'orange'}
```
五、输入为空
如果输入为空,则将创建一个空集合。以下是一个示例:
```python
s = set(input("Enter a series of items separated by commas: ").split(','))
if not s:
print("Empty set")
else:
print(s)
```
如果输入为空,则输出"Empty set"。