写出l两个列表里相同元素的代码
时间: 2023-05-29 20:04:08 浏览: 49
假设要比较的两个列表分别为list1和list2,可以使用以下代码:
方法一:使用循环和if语句
```python
same_elements = []
for i in list1:
if i in list2:
same_elements.append(i)
```
方法二:使用集合的交集
```python
set1 = set(list1)
set2 = set(list2)
same_elements = list(set1.intersection(set2))
```
相关问题
写一段python代码统计两个列表之间相同元素的个数
下面是一段简单的 Python 代码,可以统计两个列表之间相同元素的个数:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]
count = 0
for item in list1:
if item in list2:
count += 1
print("The number of common elements between the two lists is:", count)
```
这段代码中,我们首先定义了两个列表 list1 和 list2,然后使用一个 for 循环遍历 list1 中的每个元素。在循环中,我们使用 if 语句判断当前元素是否也在 list2 中出现过。如果是,我们就将计数器 count 加 1。
最后,我们输出了 count 的值,表示两个列表之间相同元素的个数。在这个例子中,输出的结果是 3,因为 list1 和 list2 之间有 3 个共同的元素:3、4 和 5。
Python里两个列表找出相同的元素
可以使用集合的交集操作来找出两个列表中相同的元素。
例如:
```python
list1 = [1,2,3,4,5]
list2 = [3,4,5,6,7]
set1 = set(list1)
set2 = set(list2)
common_elements = set1.intersection(set2)
print(common_elements)
```
输出结果为:
```
{3, 4, 5}
```
说明在两个列表中都存在元素 3、4、5。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)