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.
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With