user1079404
user1079404

Reputation: 308

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.

Upvotes: 7

Views: 33357

Answers (6)

Sarwagya
Sarwagya

Reputation: 166

Here you go (Python3)

try:

[print(*oneSet, sep=", ") for oneSet in a]

For some a:

a=[["tables", 1, 2], ["ladders", 2, 5], ["chairs", 2]]

print(*list) opens up the list into elements in the print command. You can use a parameter sep=string to set the separator. :)

Upvotes: 0

codewizard
codewizard

Reputation: 406

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.

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 360685

This uses pure list comprehensions without map(), re.sub() or a for loop:

print '\n'.join((item[0] + ' ' + ', '.join(str(i) for i in item[1:])) for item in l)

Upvotes: 0

jordanm
jordanm

Reputation: 35014

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

Upvotes: 3

ovgolovin
ovgolovin

Reputation: 13430

Try this:

L = [['tables', 1, 2], ['ladders', 2, 5], ['chairs', 2]]
for el in L:
    print('{0} {1}'.format(el[0],', '.join(str(i) for i in el[1:])))

The output is:

tables 1, 2
ladders 2, 5
chairs 2

{0} {1} is the output string where

{0} is equal to el[0] which is 'tables', 'ladders', ...

{1} is equal to ', '.join(str(i) for i in el[1:])

and ', '.join(str(i) for i in el[1:]) joins each element in the list from these: [1,2], [2,5],... with ', ' as a divider.

str(i) for i in el[1:] is used to convert each integer to string before joining.

Upvotes: 0

NPE
NPE

Reputation: 500903

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

Upvotes: 9

Related Questions