python头歌实训作业答案元组与集合
时间: 2023-09-01 08:11:35 浏览: 399
1. 元组
题目1:
```python
# 将元组 (1,2,3,4,5,6,7,8,9,10) 反转后输出
tup = (1,2,3,4,5,6,7,8,9,10)
new_tup = tup[::-1]
print(new_tup)
```
输出结果:
```
(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
```
题目2:
```python
# 将元组 ('a', 'b', 'c', 'd', 'e', 'f') 转换成列表
tup = ('a', 'b', 'c', 'd', 'e', 'f')
new_list = list(tup)
print(new_list)
```
输出结果:
```
['a', 'b', 'c', 'd', 'e', 'f']
```
题目3:
```python
# 判断元素 'a' 是否在元组 ('a', 'b', 'c', 'd', 'e', 'f') 中
tup = ('a', 'b', 'c', 'd', 'e', 'f')
if 'a' in tup:
print("元素 'a' 在元组中")
else:
print("元素 'a' 不在元组中")
```
输出结果:
```
元素 'a' 在元组中
```
2. 集合
题目1:
```python
# 创建一个集合,包含数字 1 到 10,并输出
num_set = set(range(1, 11))
print(num_set)
```
输出结果:
```
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
```
题目2:
```python
# 将两个集合 {1,2,3,4,5} 和 {4,5,6,7,8} 合并成一个集合,并输出
set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
set3 = set1.union(set2)
print(set3)
```
输出结果:
```
{1, 2, 3, 4, 5, 6, 7, 8}
```
题目3:
```python
# 从集合 {1,2,3,4,5,6,7,8,9,10} 中删除数字 5,并输出
num_set = {1,2,3,4,5,6,7,8,9,10}
num_set.discard(5)
print(num_set)
```
输出结果:
```
{1, 2, 3, 4, 6, 7, 8, 9, 10}
```
阅读全文