Crear una lista dentro de una lista - no funciona

Ok so I am having a problem whereby I need to make another list from a list I have already split. Here is the code.

def lists():
  instructionList = instructions()
  Lists = instructionList.split('\n')
  Instructions = []
  for values1 in Lists:
    Instructions = Instructions + [values1.split(",")]
    for values2 in Instructions:
      newLists = []
      newLists = newLists + [values2.split(" ")]
  print Instructions [3]

When I create the Instructions list it works, but when I try this further to create newLists it gives me this error=> The error was:'list' object has no attribute 'split' Attribute not found. You are trying to access a part of the object that doesn't exist.

I need to keep breaking the same list down. Also I am very new to this so please explain things carefully to me.

preguntado el 05 de mayo de 13 a las 20:05

Utilice las append() to add values to a list. -

I'm not wanting to add values I am wanting to break the list down using xxx.split. But it won't continue letting me do it -

2 Respuestas

El problema es que values1.split(",") evaluates to a list, which you then put inside another list and append to Instructions. La variable Instructions then holds a list of lists. So, each element assigned to values2 will be of type list.

Entonces, si es original instructions parece: "a,b,c\nx,y,z\n"

Lists termina pareciendo: ["a,b,c" , "x,y,z"]

Entering the outer loop, values1 first is: "a,b,c"

¿Entonces Instructions = Instructions + [values1.split(",")] da: [ ["a" , "b" , "c"] ]

Then, when you go into the inner loop, values2 starts as: [ "a" , "b" , "c" ]

In other words, that's a list, which doesn't support split.

Beyond that, I'm actually not clear what you're trying to do with this code (what is the purpose of the inner loop?). If your goal is to get a list of lists, just remove that inner loop entirely. If you want one flat list, remove the square brackets around [values1.split(",") so that you're just appending two lists (and, again, remove that inner loop).

contestado el 05 de mayo de 13 a las 20:05

Because values2 is not a list it is a variable in Instructions! like Instructions[0] etc

contestado el 05 de mayo de 13 a las 20:05

So why does values1 work then? I'm not questioning you just confused and I have no idea how to fix it? - Danrex

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.