0

I have a list like this

list=[[2,3],[3,4]] 

I want to print each list in the list like this:
1: 2 3, 2: 3 4
So the first part is the position of the list in the list followed by the numbers in the list. So far i've tried a for loop and a single print line. The for loop works but prints every list in a new line. The other print statement looks like this but it doesn't work at all and i have no idea how to fix it.

print('{0:}:'.format(list[0]),' '.join([', '.join([str(e) for e in slist]) for slist in list]))

For this the list looked like this list = [[1,2,3],[2,3,4]] so the first element in each list is the index for the list (starts at 1) I use Python3

2
  • using list a variable name is bad practice Commented Nov 14, 2014 at 19:04
  • it's just for the question here. but thanks! Commented Nov 14, 2014 at 19:06

2 Answers 2

3
l =[[2,3],[3,4]]
print(", ".join(["{}: {}".format(ind," ".join(map(str,x))) for ind, x in enumerate(l,1)]))
1: 2 3, 2: 3 4

enumerate(l,1) keeps track of the index of the sublists, we pass 1 as the second parameter to start the indexing at 1 instead of `0.

" ".join(map(str,x) maps all the ints to strings and we use str.format to add : before each index. ", ".join separates each section with a comma.

Sign up to request clarification or add additional context in comments.

1 Comment

@iCodez, lol yes I suppose it does, there does not seem to be any simple way to do it. I will add some explanation though :).
0

you can use join() and enumerate() in a list comprrehension :

>>> l=[[2,3],[3,4]]
>>> ','.join(['{}:{}'.format(i,' '.join(str(t) for t in j)) for i,j in enumerate(l,1)])
'1:2 3,2:3 4'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.