Filling a list of lists...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • RodAG
    New Member
    • Mar 2012
    • 6

    Filling a list of lists...

    Here's my problem.
    I need a matrix (a list of lists) of undefined size (maybe I should define it as an empty list?). The matrix will have a size of nxm but n and m will be introduced by the user.
    Now, the user will also introduce the values for the matrix as a string, for example: list[0]="Hello" but I need to store that string as a list of 5 elements list[0]=[H, e, l, l, o]
    Is there a not so complicated way to do that?

    So far what I'm thinking is to define an empty list list=[] and then to ask for the number of lines the matrix will have, then to change the size of list according to the value introduced (no idea on how to do that). Once the list has the desired size, I'd ask for each of the strings and convert it to list using list(string) (I know there's such a function, but not sure if it works on lists inside a list)...
    well, that's my idea. Python is the very first programming language I try to learn and don't know how to write it properly, so forgive me if this is a super easy thing and I'm drawning in my own ignorance.


    Thanks for any tips and sorry for the long post.
    -RodAG
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    See if this helps:
    Code:
    >>> cols = 6
    >>> rows = 4
    >>> m = [[None for i in range(cols)] for j in range(rows)]
    >>> m[0]
    [None, None, None, None, None, None]
    >>> word = "Hello"
    >>> word[:6]
    'Hello'
    >>> for i, letter in enumerate(word[:cols]):
    ... 	m[0][i] = letter
    ... 	
    >>> m[0]
    ['H', 'e', 'l', 'l', 'o', None]
    >>>

    Comment

    • RodAG
      New Member
      • Mar 2012
      • 6

      #3
      @bvdet

      Thanks for your reply. I tried the code and it worked perfectly. I made some minor modifications so it asked the user for the size of the matrix:
      Code:
      cols=input("How many columns will be in the matrix?: ")
      rows=input("How many rows will be in the matrix?: ")
      I also implemented a While function so it asked the user to write as many strings as rows, each one as long as the number of columns:

      Code:
      while k<rows:
          String=raw_input("Write a string: ")
          for i, letter in enumerate(Seq[:cols]):
              m[k][i]=letter
          k=k+1
      Thanks again, the code you provided was extremely useful.
      -RodAG

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        You're welcome. :)

        Sometimes a code snippet is all that it takes to point someone in the right direction.

        Comment

        Working...