【问题标题】:'list indices must be integers, not tuple" in pythonpython中的“列表索引必须是整数,而不是元组”
【发布时间】:2016-11-04 07:10:02
【问题描述】:

我正在开发一个 python 项目,我无法使用这些值绘制图表。我无法纠正错误,因为我无法找出引发错误的列表。我在下面提供了错误

import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle

X = [[ 0.24459249,0.11983918,-0.85683004,-0.89438038,-0.50183492],
 [-0.7976035,1.95307959,-1.25068375,-0.00678967,-0.25262571],
 [ 0.34136607,0.92766956,0.66223556,-1.46454436,-1.60347224], 
 [ 2.22677877,1.55027737,-0.02381159,-0.05812014,0.17297636],
 [ 0.20753675,-1.00847549,-0.13858473,-0.93317858,0.18550176],
 [ 1.38946893,-1.03658362,-0.62923293,1.44856682,0.59064268]]

y = [ 0,2,1,0,0,0,3,0,2,1,0,0,2,0,0,0,1,0,
  0,0,0,0,1,3,4,0,0,0,0,3,0,2,1,0,0,0,
  3,1,3,0,4,0,0,0,1,4,0,4,0,0,0,0,2,0,
  1,1,1,1,0,0,2,0,1,0,2,2,1,0,2,1,0,3,
  1,1,1,0,1,0,0,3,0,0,0,3,0,0,0,0,0,0,
  0,3,0,0,0,1,2,3,0,0,0,0,0,0,3,0,2,1,
  2,3,1,1,0,2,2,0,0,0,3,2,3,4,0,3,1,0,
  3,3,0,0,0,0,0,0,0,0,4,3,1,0,0,1,0,1,
  0,1,4,0,0,0,0,0,0,4,3,1,1,1,2,0,0,4,
  0,0,0,0,0,0,1,0,3,0,1,0,4,1,0,1,0,0,
  3,2,0,0,1,0,0,2,1,2,0,3,1,2,0,3,0,0,
  0,1,0,0,0,0,0,3,3,3,0,1,0,4,0,3,1,0,
  0,0,0,0,0,0,0,3,1,0,0,0,3,2,0,2,1,0,
  0,3,2,1,0,0,0,0,0,2,0,2,2,1,3,0,0,1,
  0,0,0,0,0,0,0,1,0,3,0,0,4,2,2,2,1,0,
  1,0,2,0,1,0,0,0,1,0,2,0,3,0,2,4,2,0,
  0,0,1,0,2,2,1,0,3,1,1,2,3,1,0]


def plot_2D(data, target, target_names):
     colors = cycle('rgbcmykw')
     target_ids = range(len(target_names))
     plt.figure()
 for i, c, label in zip(target_ids, colors, target_names):
     plt.scatter(data[target == i, 0], data[target == i, 1],
                c=c, label=label)
 plt.legend()
 plt.savefig('Reduced_PCA_Graph')



target_names = [0,1,2,3,4]
plot_2D(X, y, target_names)

错误是

Traceback (most recent call last):
  File "mat.py", line 49, in <module>
    plot_2D(X, y, target_names)
  File "mat.py", line 40, in plot_2D
    plt.scatter(data[target == i, 0], data[target == i, 1],
TypeError: list indices must be integers, not tuple

【问题讨论】:

  • 请始终包含完整的错误回溯。也就是说,X,因此data 是一个列表列表。像 data[target == i, 0] 这样的花哨索引只适用于类似 numpy 的数组对象。
  • 我认为你的数据集 X 有问题,请检查一下。

标签: python matplotlib graph


【解决方案1】:

我不确定,但也许你想这样:

def plot_2D(data, target, target_names):
    colors = cycle('rgbcmykw')
    target_ids = range(len(target_names))
    plt.figure()
    for i, c, label in zip(target_ids, colors, target_names):
        plt.scatter(data[target[i]][0], data[target[i]][1], c=c, label=label)
    plt.legend()
    #plt.savefig('Reduced_PCA_Graph')
    plt.show()

【讨论】:

    猜你喜欢
    • 2014-03-06
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    • 2012-03-11
    • 2017-02-11
    • 1970-01-01
    相关资源
    最近更新 更多