我有一个包含不同长度值的嵌套:
[['cat', 123, 'yellow'],
['dog', 12345, 'green'],
[horse', 123456, 'red']]
我要像这样打印它们:
cat, 123, yellow
dog, 12345, green
horse, 123456, red
我尝试使用pprint通过以下代码实现目标:
for sub in master_list:
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(sub)
其中master是嵌套列表,子列表是其中的子列表。但是,这给了我这样的输出:
[
'cat',
123,
'yellow'
],
[
'dog',
12345,
'green'
],
[
horse',
123456,
'red'
]
是否有一个python模块,可以让我相对容易地实现所需的功能,而无需进行复杂的修改?
谢谢
答案 0 :(得分:2)
您可以使用以下代码:
INotifyPropertyChanged
正在像这样打印输出:
myLst = [['cat', 123, 'yellow'],
['dog', 12345, 'green'],
['horse', 123456, 'red']]
for subLst in myLst:
print("\t".join([str(ele) for ele in subLst]))
如果您也想使用“,”,只需更改该行
cat 123 yellow
dog 12345 green
horse 123456 red
到
print("\t".join([str(ele) for ele in subLst]))
完整的东西作为单线:
print(",\t".join([str(ele) for ele in subLst]))
或者如果您需要一个功能:
print("\n".join([",\t".join([str(ele) for ele in subLst]) for subLst in myLst]))
修改
正如评论中指出的那样,这也是python def printLst(myLst):
print("\n".join([",\t".join([str(ele) for ele in subLst]) for subLst in myLst]))
函数的一个很好的用例。可以使用它来缩短内容;)
答案 1 :(得分:2)
熊猫可以提供帮助。
import pandas as pd
lst = [['cat', 123, 'yellow'], ['dog', 12345, 'green'], ['horse', 123456, 'red']]
df = pd.DataFrame(lst)
print(df)
输出:
0 1 2
0 cat 123 yellow
1 dog 12345 green
2 horse 123456 red
答案 2 :(得分:0)
您可以使用此:
a = [['cat', 123, 'yellow'], ['dog', 12345, 'green'], ['horse', 123456, 'red']]
# Get the max length of string in the list
m = max([len(str(x)) for y in a for x in y])
# Use the format specifier in Python print function:
# Example: print '{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98)
# This prints : xxx 123 98.00
# We will create the string as {:6s}, here 6 is the length in our case and will be generated dynamically using 'm'
list(map(lambda x: print('\t'.join(list(map(lambda y: str('{' + ':{m}s'.format(m=m) +'}').format(str(y)), x)))), a))
输出:
cat 123 yellow
dog 12345 green
horse 123456 red
答案 3 :(得分:0)
您的具体格式愿望可以通过使用ljust
打印并添加所需的空格来解决:
data = [['cat', 123, 'yellow'],
['dog', 12345, 'green'],
['horse', 123456, 'red']]
# get the overall widest string as base for right-aligning them
max_len = max( len(str(x)) for k in data for x in k)
for inner in data:
first = True
for elem in inner[:-1]: # all but the last
text = "{},".format(elem).ljust(max_len+2)
print(text,end="")
print(inner[-1]) # print last
输出:
cat, 123, yellow
dog, 12345, green
horse, 123456, red
Doku:
通常,您可以使用string format mini language来格式化自己喜欢的输出格式:
for inner in data:
first = True
for elem in inner:
if first:
text = "{:<{}} ".format(elem,max_len+2)
first = False
else:
text = ", {:<{}} ".format(elem,max_len+2)
print(text, end="")
print("")
输出:
cat , 123 , yellow
dog , 12345 , green
horse , 123456 , red
格式字符串"{:<{}} ".format(elem,max_len+2)
格式element
右对齐为max_len+2
个字符。 first
只是为了使您的,
不在行首。
答案 4 :(得分:0)
您可以这样做:
globalTeardown
spacing = [max(map(lambda x: len(str(x)), d)) for d in zip(*data)]
for row in data:
for i, elem in enumerate(row):
e = str(elem) + (',' if i < len(row) -1 else '')
print('{{:{}}} '.format(spacing[i]+1).format(e), end='')
print()
cat, 123, orange
elephant, 500000, green
horse, 123456.0, red
的定义是先收集数据中每个“列”的最大长度。我们可以使用以下方式对列进行分组:
spacing
这样可以提供您的数据的转置副本:
zip(*data)
然后,我们使用('cat', 'elephant', 'horse'),
(123, 500000, 123456.0),
('orange', 'green', 'red')
函数将map
函数应用于这些列:
len(str(x))
然后,我们只获取每一列的(3, 8, 5),
(3, 6, 8),
(6, 5, 3)
,将所有内容组合成列表推导式,然后将其返回为max
:
spacing
然后,当我们遍历您的数据时,我们也想spacing = [max(map(lambda x: len(str(x)), d)) for d in zip(*data)]
,以便知道我们正在使用哪个“列”。除了实际的enumerate(row)
之外,i
还可以为您提供该列的索引。
之后,如果不是最后一个元素,我们将分配一个临时elem
来附加逗号:
str
这使它更具可读性,然后将其添加为格式参数的一部分。
然后,我们使用字符串格式(如果需要,也可以使用e = str(elem) + (',' if i < len(row) -1 else '')
)基于该列添加预定义的最大值e.ljust(spacing[i] + 1)
。请注意,我们通过先转义外部大括号(spacing
和{{
)来格式化字符串两次,因此它可以按顺序排列:
}}
请注意,使用'{{:{}}}.format(9).format(e)
# becomes
'{:9}'.format(e)
# becomes
'cat, '
可以使打印行连续,直到end=''
完成为止。 row
用于说明添加的逗号。
我必须承认,这可能不是最有效的方法,但是根据您要实现的解决方案而定,可能会大不相同。
答案 5 :(得分:0)
另一种方式,给出嵌套列表:
table = [['cat', 123, 'yellow'],
['dog', 12345, 'green'],
['horse', 123456, 'red']]
使用字符串方法:
for line in table:
print("|", end='')
for word in line:
print (f" {word}".ljust(10) + "|", end='')
print()
获得:
| cat | 123 | yellow |
| dog | 12345 | green |
| horse | 123456 | red |