繁体   English   中英

打印列表列表,不带括号

[英]Printing a list of lists, without brackets

在这里问了一个有点类似的问题,但答案没有帮助。

我有一个列表列表,特别是像..

[[tables, 1, 2], [ladders, 2, 5], [chairs, 2]]

它旨在成为一个简单的索引器。

我打算像这样输出它:

tables 1, 2
ladders 2, 5
chairs 2

虽然我不能得到相当的输出。

但是我可以得到:

tables 1 2
ladders 2 5
chairs 2

但这还不够接近。

有没有一种简单的方法可以做我要问的事情? 这并不是该计划的难点。

以下将做到这一点:

for item in l:
  print item[0], ', '.join(map(str, item[1:]))

其中l是你的名单。

对于您的输入,这会打印出来

tables 1, 2
ladders 2, 5
chairs 2

如果您不介意输出在单独的行上:

foo = [["tables", 1, 2], ["ladders", 2, 5], ["chairs", 2]]
for table in foo:
    print "%s %s" %(table[0],", ".join(map(str,table[1:])))

把这一切都放在同一条线上会使它稍微困难一些:

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

在 Python 3.4.x 中

以下将做到这一点:

for item in l:
    print(str(item[0:])[1:-1])

其中 l 是你的名单。

对于您的输入,这会打印出:

tables 1, 2
ladders 2, 5
chairs 2

另一种(更清洁)的方式是这样的:

for item in l:
    value_set = str(item[0:])
    print (value_set[1:-1])

产生相同的输出:

tables 1, 2
ladders 2, 5
chairs 2

希望这可以帮助任何可能遇到此问题的人。

给你(Python3)

尝试:

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

对于一些:

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

print(*list) 在打印命令中将列表打开为元素。 您可以使用参数 sep=string 来设置分隔符。 :)

试试这个:

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:])))

输出是:

tables 1, 2
ladders 2, 5
chairs 2

{0} {1}是输出字符串,其中

{0}等于el[0] ,即'tables' , 'ladders' , ...

{1}等于', '.join(str(i) for i in el[1:])

', '.join(str(i) for i in el[1:])连接列表中的每个元素: [1,2] , [2,5] ,... with ', ' as a分隔线。

str(i) for i in el[1:]用于在加入之前将每个整数转换为字符串。

这使用没有map()re.sub()for循环的纯列表re.sub()

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

暂无
暂无

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

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