Getting a string from a list in a list

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Magnie
    New Member
    • Mar 2010
    • 3

    Getting a string from a list in a list

    I am making a game, and I'm wondering how I can get a string( /element ) out of a list in a list.

    Code:
    players = [["Magnie","apassword"],["Test","apassword"]]
    if username == players[0[0]] and password == players[0[1]]:
        print "Welcome back,",username+"!"
    Something like that? ( That's not the real code, just something that I want. ;) )
  • YarrOfDoom
    Recognized Expert Top Contributor
    • Aug 2007
    • 1243

    #2
    Almost correct, it's players[i][j] instead of players[[i]j] (where i and j are of course the actual values you want to use, or a variable holding that value).

    Comment

    • leegao
      New Member
      • Mar 2010
      • 3

      #3
      One way of doing this is to convert the 2d list into a dictionary via {}.update()
      Code:
      players_dict = {}
      players_dict.update(players)
      if username in players_dict: 
          if password == players_dict[username]:
              print "Welcome back,",username+"!"

      Another (shorter, but messier) way:
      Code:
      lst = zip(*players)[0]
      if username in lst:
          print "Welcome back" if password == players[lst.index(username)][1] else "Wrong Password"

      Comment

      • Magnie
        New Member
        • Mar 2010
        • 3

        #4
        Yarr: Ohh, thanks! I thought that if a list is inside a list it would make more sense to do it the other way. :P Thanks again!

        Comment

        Working...