简体   繁体   中英

iterating through list of list and dictionary python

I have this code in Python:

from pprint import pprint

def addDictionary(States,Transition,Languaje,Tr):
    for s in States :
         D = {}
         Transition[s] = D # this create {"state1":{"symbol1":}}
         for l in Languaje:
            for i in range(len(Tr)):
               D[l] = Tr[i][0]

def addStates(States):
     cant = int(raw_input("how many states?: "))
     for i in range(cant):
          c = "q"+str(i)
          States.append(c)

def addLan(Languaje):
     c = int(raw_input("how many symbols?: "))
     for j in range(c):
          l = raw_input("symbol: ")
          Languaje.append(l)

if __name__ == "__main__":

      States=[]
      Languaje=[]
      Transition={} #{"state":{"symbol1":"transition value","symbol2":"transition value"}}
      Tr=[["q2","q1"],["","q2"]] #transition values
      addStates(States)
      addLan(Languaje)
      addDictionary(States,Transition,Languaje,Tr)

      pprint(Transition)

and this is the output:

{'q0': {'a': '', 'b': ''}, 'q1': {'a': '', 'b': ''}}

what I want is something like this:

{'q0': {'a': 'q2', 'b': 'q1'}, 'q1': {'a': '', 'b': 'q2'}}

I want to put the values of the list Tr in my dictionary. This is only a example code. I want to implement a Deterministic Finite Automata that I developed for a class at my University

I forgot to mention that to prove the code first input 2 ,and then 2 and then a and b because I only want to prove my code with a list of 2x2. Later I will change for a nxm list. (Sorry for my "medium" skills in English :V)

One more thing: the problem is in the the function addDictionary() .

This:

def addDictionary(States, Transition, Languaje, Tr):
    for s, t in zip(States, Tr):
        Transition[s] = dict(zip(Languaje, t))

generate this output:

{'q0': {'a': 'q2', 'b': 'q1'}, 'q1': {'a': '', 'b': 'q2'}}

for two states and symbols a and b .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM