简体   繁体   English

在Python中以特定方式打印列表

[英]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 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. 到目前为止,我已经尝试过for循环和单个打印行。 The for loop works but prints every list in a new line. for循环有效,但在换行中打印每个列表。 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 为此,列表看起来像这个list = [[1,2,3],[2,3,4]]所以每个列表中的第一个元素是列表的索引(从1开始),我使用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. enumerate(l,1)跟踪子列表的索引,我们将1作为第二个参数传递以从1开始而不是从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. " ".join(map(str,x)将所有int映射到字符串,我们使用str.format在每个索引之前添加:", ".joinstr.format将每个节用逗号分隔。

you can use join() and enumerate() in a list comprrehension : 您可以在列表推导中使用join()enumerate()

>>> 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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