phtyon编写程序,已知两个列表 L1-[1,2,3,40,12=15,6,7,81,计算两个列表的交 集、并集和差集
时间: 2024-02-25 19:56:34 浏览: 25
你可以使用Python的集合(set)来计算两个列表的交集、并集和差集。以下是示例代码:
```python
# 已知两个列表
L1 = [1, 2, 3, 40, 12, 15, 6, 7, 81]
L2 = [2, 40, 6, 81, 100]
# 计算交集
intersection = set(L1) & set(L2)
print("交集为:", intersection)
# 计算并集
union = set(L1) | set(L2)
print("并集为:", union)
# 计算差集
difference = set(L1) - set(L2)
print("L1与L2的差集为:", difference)
difference = set(L2) - set(L1)
print("L2与L1的差集为:", difference)
```
输出结果应该为:
```
交集为: {2, 40, 6, 81}
并集为: {1, 2, 3, 100, 6, 7, 40, 81, 12, 15}
L1与L2的差集为: {1, 3, 7, 12, 15}
L2与L1的差集为: {100}
```
希望能帮到你!
相关问题
python 编写程序,计算Sn=1-3+5-7+9-11+……。
可以这样写:
s = 0 #初始化 Sn 的值
n = int(input('请输入需要计算的项数:'))
for i in range(n):
sign = (-1) ** i
num = 2 * i + 1
s += sign * num
print('计算结果为:', s)
PS: 如果您有其他问题欢迎继续提问~
编写Python程序,计算Sn=2-4+6-8+10-12+…。
这个数列中,每两个相邻的数之差都是2,且第一个数是2,因此可以使用循环来计算。
代码如下:
```python
n = int(input("请输入要计算的项数:"))
sum = 0
for i in range(1, n+1):
a = 2 + (i-1)*2
b = 4 + (i-1)*2
sum += a - b
print("前{}项的和为:{}".format(n, sum))
```
解释一下代码:
- 第一行从用户处获取要计算的项数。
- 第二行初始化总和为0。
- 第三行开始循环,每次计算两个相邻的数并求差,然后加到总和中。
- 第四行使用format函数将计算结果输出。
运行程序,输入要计算的项数,例如输入10,输出结果为:
```
请输入要计算的项数:10
前10项的和为:-55
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)