使用列表列表时出现TypeError

时间:2018-02-15 06:17:15

标签: python list append

我正在尝试将XY坐标从列表附加到另一个列表,以便我可以在15个不同对象的散点图周围绘制补丁。但是在尝试运行代码时出现错误TypeError: list indices must be integers or slices, 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

1 个答案:

答案 0 :(得分:4)

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

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