Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a list of lists, without brackets

A somewhat similar question was asked on here but the answers did not help.

I have a list of lists, specifically something like..

[[tables, 1, 2], [ladders, 2, 5], [chairs, 2]]

It is meant to be a simple indexer.

I am meant to output it like thus:

tables 1, 2
ladders 2, 5
chairs 2

I can't get quite that output though.

I can however get:

tables 1 2
ladders 2 5
chairs 2

But that isn't quite close enough.

Is there a simple way to do what I'm asking? This is not meant to be the hard part of the program.

like image 788
user1079404 Avatar asked Dec 03 '11 20:12

user1079404


3 Answers

The following will do it:

for item in l:
  print item[0], ', '.join(map(str, item[1:]))

where l is your list.

For your input, this prints out

tables 1, 2
ladders 2, 5
chairs 2
like image 172
NPE Avatar answered Sep 24 '22 03:09

NPE


If you don't mind that the output is on separate lines:

foo = [["tables", 1, 2], ["ladders", 2, 5], ["chairs", 2]]
for table in foo:
    print "%s %s" %(table[0],", ".join(map(str,table[1:])))

To get this all on the same line makes it slightly more difficult:

import sys
foo = [["tables", 1, 2], ["ladders", 2, 5], ["chairs", 2]]
for table in foo:
    sys.stdout.write("%s %s " %(table[0],", ".join(map(str,table[1:]))))

print
like image 28
jordanm Avatar answered Sep 21 '22 03:09

jordanm


In Python 3.4.x

The following will do it:

for item in l:
    print(str(item[0:])[1:-1])

where l is your list.

For your input, this prints out:

tables 1, 2
ladders 2, 5
chairs 2

Another (cleaner) way would be something like this:

for item in l:
    value_set = str(item[0:])
    print (value_set[1:-1])

Yields the same output:

tables 1, 2
ladders 2, 5
chairs 2

Hope this helps anyone that may come across this issue.

like image 29
codewizard Avatar answered Sep 22 '22 03:09

codewizard