简体   繁体   中英

Print list in specific way in Python

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

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM