在Python中,查找两个列表中相同的数据可以通过多种方法实现,以下是几种常见的方法:
1. 使用集合(set)的交集运算符 `&`:
```python
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common_elements = list(set(list1) & set(list2))
print(common_elements) 输出: [4, 5]
2. 使用 `collections.Counter` 类:
```python
from collections import Counter
list1 = [1, 2, 3, 4, 2, 3, 5]
counter = Counter(list1)
duplicates = [item for item, count in counter.items() if count > 1]
print(duplicates) 输出: [2, 3]
3. 使用循环和计数器:
```python
def find_duplicates(lst):
duplicates = []
for item in lst:
if lst.count(item) > 1 and item not in duplicates:
duplicates.append(item)
return duplicates
my_list = [1, 2, 3, 4, 2, 3, 5]
print(find_duplicates(my_list)) 输出: [2, 3]
4. 使用 `pandas` 库来处理表格数据:
```python
import pandas as pd
data1 = {'A': [1, 2, 3, 4, 5]}
data2 = {'B': [4, 5, 6, 7, 8]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
common_data = pd.merge(df1, df2, on=['A', 'B'], how='inner')
print(common_data) 输出:A2
B4
以上方法适用于列表数据。如果需要处理Excel表格中的数据,可以使用 `openpyxl` 或 `pandas` 等库。例如,使用 `openpyxl` 查找Excel中两列相同的数据:
```python
import openpyxl
打开工作簿
wb = openpyxl.load_workbook('path_to_your_excel_file.xlsx')
选取sheet
sh = wb['Sheet1']
定义两个用于存放数据的list
list1 = []
list2 = []
将excel的两列存入list中
for data in list(sh.rows)[0:]: 如果需要去掉第一行的表头就从1开始
list1.append(data.value) 将第一列数据存入list1
list2.append(data.value) 将第二列数据存入list2
查找相同数据
for i in range(len(list1)):
for j in range(len(list2)):
if list1[i] == list2[j]:
将相同数据写入第三列
sh.cell(row=i+1, column=3, value=list1[i])
保存数据,关闭excel
wb.save('path_to_your_excel_file.xlsx')
请根据你的具体需求选择合适的方法