gpt4 book ai didi

python - 使用列表列表时出现 TypeError

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:40 24 4
gpt4 key购买 nike

我正在尝试将 XY 坐标从一个列表 append 到另一个列表,这样我就可以在 15 个不同对象的散点图周围绘制补丁。但是在尝试运行代码时出现错误,TypeError: list indices must be integers or slice, not tuple

我正在处理的数据集是横向格式化的。读取的数据会生成 x 坐标列表和 y 坐标列表。

数据集示例:

data = [[],[]]
data[0] = [random.sample(range(80), 10) for _ in range(6)] #x-coordinates
data[1] = [random.sample(range(80), 10) for _ in range(6)] #y-coordinates

x_data = data[0]
y_data = data[1]

我绘制了一个散点图,然后想在该散点图周围添加不​​同半径的圆。我这样绘制散点图,效果很好:

scatter = ax.scatter(x_data[0], y_data[0], zorder = 5, s = 20) 

我在使用以下代码时遇到错误:

#creating list of patches
players = []
for n in range(10):
##as there are always 3 circles, append all three patches as a list at once
players.append([
mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 2, color = 'black', lw = 1, alpha = 0.8, zorder = 4),
mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 4, color = 'gray', lw = 1, alpha = 0.8, zorder = 3),
mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 6, color = 'lightgrey', lw = 1, alpha = 0.8, zorder = 2)
])

##adding patches to axes
for player in players:
for circle in player:
ax.add_patch(circle)

我得到了

的错误
mpl.patches.Circle((x_data[0,n],y_data[0,n]), radius = 2, color = 'black', lw = 1, alpha = 0.8, zorder = 4),

TypeError: list indices must be integers or slices, not tuple

最佳答案

错误不言而喻。这是因为 x_data 是一个列表。它不支持多重索引。如果你想这样做,请将 x_data 转换为 numpy 数组。否则你也可以做x_data[0][n]

此外,您有一个从 0 到 14 的循环,但是您的 x_datay_data 的形状为 (6,10)。您可能需要检查一下。

关于python - 使用列表列表时出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48801000/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com