有如下两个列表: lst1 = [1, 2, 3, 2, 5, 1, 2] lst2 = [2, 7, 9, 5] 编程实现: 1. 求哪些整数既在lst1中,也在lst2中? 2. 求哪些整数在lst1中,不在lst2中? 3. 求两个列表一共有哪些整数?
时间: 2023-05-29 19:03:46 浏览: 119
python 计算两个列表的相关系数的实现
1. 使用集合的交集操作,即可求出既在lst1中,也在lst2中的整数:
```python
set1 = set(lst1)
set2 = set(lst2)
common_set = set1.intersection(set2)
common_list = list(common_set)
print(common_list)
```
输出结果为:[2, 5]
2. 使用集合的差集操作,即可求出在lst1中,不在lst2中的整数:
```python
set1 = set(lst1)
set2 = set(lst2)
diff_set = set1.difference(set2)
diff_list = list(diff_set)
print(diff_list)
```
输出结果为:[1, 3]
3. 使用集合的并集操作,即可求出两个列表一共有哪些整数:
```python
set1 = set(lst1)
set2 = set(lst2)
union_set = set1.union(set2)
union_list = list(union_set)
print(union_list)
```
输出结果为:[1, 2, 3, 5, 7, 9]
阅读全文