【问题标题】:TypeError when using a list of lists使用列表列表时出现 TypeError
【发布时间】:2018-02-15 06:17:15
【问题描述】:

我正在尝试将 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

【问题讨论】:

    标签: python list append


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      • 2015-11-20
      • 2018-10-07
      相关资源
      最近更新 更多