基本的python误解dict(TypeError:字符串索引必须是整数)

时间:2016-11-24 11:44:24

标签: python string dictionary

我开始学习python,我尝试使用pyQt制作图灵机应用程序。我从QTextEdit某些“代码”中获取并将其放入dict并得到类似的内容:

{'1': {'a': ['s', 'D', '2'], 's': ['s', 'G', '2']}, '2': {'a': ['a', 'D', '1']}}

我有这个函数table是Dict:

def execute_TM(self, table, ruban, etat1):
    self.Ruban.position = 1
    self.table = table
    etatAct = etat1
    while etatAct != 'stop':
        symb = self.Ruban.lire_cellules()
        # print symb
        print self.table
        nvSymb = self.table[etatAct][symb][0]
        self.Ruban.ecrire(nvSymb)
        if table[etatAct][symb][1] == 'D':
            self.Ruban.deplacement_droite()
        if table[etatAct][symb][1] == 'G':
            self.Ruban.deplacement_gauche()
        else:
            print
            "erreur code deplacement"
        etatAct = table[etatAct][symb][2]

我收到了这个错误:

nvSymb = self.table[etatAct][symb][0]
TypeError: string indices must be integers

我一直在阅读很多关于这个错误的帖子,并尝试了不同的东西......但我还是不明白。

修改: 感谢您的帮助,我正在努力理解,所以如果我有:

table={'1': {'a': ['s', 'D', '2'], 's': ['s', 'G', '2']}, '2': {'a': ['a', 'D', '1']}}

然后我想从主键'1'和密钥's'获取列表的第二个元素:'G' 我可以致电table['1']['s'][1],如下所示:

table["here it's a string"]["here it's also a string"]["here it's an integer"]

它的工作原理:

>>> table={'1': {'a': ['s', 'D', '2'], 's': ['s', 'G', '2']}, '2': {'a':['a', 'D', '1']}}
>>> etatAct='1'
>>> symb='s'
>>> table[etatAct][symb][1]
'G'

我仍然不明白为什么它在函数中不起作用....

编辑2:

使用type()我发现self.table不是dict,而是PyQt4.QtCore.QStringList有人知道如何轻松转换它吗?

3 个答案:

答案 0 :(得分:3)

你会明白这是什么错误,

In [10]: a = 'Hellooo'
In [11]: print a[0]
H
In [12]: print a['0']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-175cb7ceb755> in <module>()
----> 1 print a['0']

TypeError: string indices must be integers, not str
  

在您的代码中尝试使用字符串而不是字典索引字符串。

答案 1 :(得分:1)

从你的错误中可以清楚地知道(etatAct,symb)的一个索引不是整数而是字符串。

'use strict';
const express = require('express');
const templateRouter = express.Router();


templateRouter.route('/:templateName')
    .get(function(req, res) {
        if (req.params.templateName !== 'core') {
            
            res.render('./../../templates/'req.params.templateName + '/index');
            
        } else {
            res.send('error !');
        }
    });

module.exports = templateRouter;

您可以通过将其转换为整数来尝试。

nvSymb=self.table[etatAct][symb][0]
TypeError: string indices must be integers

答案 2 :(得分:1)

你应该这样做:

nvSymb=self.table[etatAct][symb][0]
分开,所以你可以看到你得到一个字符串:

tmp = self.table[etatAct]
nvSymb = tmp[symb][0]

并查看self.tableself.table[etaAct]是否是由非整数索引的字符串。从这些知识开始,你应该能够解决这个问题,纠正你的意见。