Python如何将列表中接近的值只显示一个
时间: 2023-05-19 12:01:32 浏览: 43
可以使用set()函数将列表转换为集合,然后再将集合转换回列表,这样就可以去除重复的元素。代码如下:
```python
lst = [1.2, 1.3, 1.5, 2.1, 2.2, 2.3, 3.1, 3.2, 3.5]
lst = list(set(round(i, 1) for i in lst))
print(lst)
```
输出结果为:
```
[1.2, 1.5, 2.1, 2.2, 3.1, 3.5]
```
这里使用了round()函数将浮点数保留一位小数,以便比较接近的值可以被认为是相等的。
相关问题
二值化图像中通过是否接近圆形来过滤python代码
以下是使用OpenCV库的Python代码来过滤二值化图像中是否接近圆形的方法:
```python
import cv2
# 读取二值化图像
img = cv2.imread('binary_image.png', cv2.IMREAD_GRAYSCALE)
# 使用霍夫圆变换检测圆形
circles = cv2.HoughCircles(img, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)
# 如果没有检测到圆形,返回错误信息
if circles is None:
print("No circles were detected.")
else:
# 遍历所有检测到的圆形
for i in circles[0]:
# 计算圆形的圆度,即宽高比是否接近1
circularity = 4 * 3.14 * i[2] / (i[1] ** 2)
# 如果圆度接近1,则判定为圆形
if circularity >= 0.8 and circularity <= 1.2:
# 在原图上标记出圆形位置
cv2.circle(img, (i[0], i[1]), i[2], (0, 255, 0), 2)
# 显示处理后的图像
cv2.imshow('Detected Circles', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
在这个例子中,我们使用了OpenCV库的`HoughCircles`函数来检测图像中的圆形。然后,对于每个检测到的圆形,我们计算了它的圆度,并使用一个阈值来判断它是否接近圆形。最后,在原图上标记出圆形的位置并显示出来。
给我一个python代码对excel文件相关性分析
以下是一个简单的Python程序来分析Excel文件中的相关性:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Read Excel file
df = pd.read_excel('filename.xlsx')
# Calculate correlation matrix
corr_matrix = df.corr()
# Plot correlation matrix as heatmap
fig, ax = plt.subplots()
im = ax.imshow(corr_matrix.values)
# Set labels for the x and y axis
ax.set_xticks(np.arange(len(corr_matrix.columns)))
ax.set_yticks(np.arange(len(corr_matrix.columns)))
ax.set_xticklabels(corr_matrix.columns)
ax.set_yticklabels(corr_matrix.columns)
# Rotate labels
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
# Print correlation matrix values on heatmap
for i in range(len(corr_matrix.columns)):
for j in range(len(corr_matrix.columns)):
text = ax.text(j, i, round(corr_matrix.values[i, j],2),
ha="center", va="center", color="w")
# Set title and show heatmap
ax.set_title("Correlation Matrix")
plt.show()
```
其中,您需要将 `filename.xlsx` 更改为您要分析的Excel文件的名称。此程序将读取Excel文件的数据,并计算数据的相关性矩阵。然后,它将使用热图绘制相关性矩阵。相关性矩阵显示每个变量之间的相关程度。更接近1的值表示正相关,而更接近-1的值表示负相关。值越接近0,表示这两个变量之间基本没有相关性。