简体   繁体   English

如何在Python 3.6中根据需要打印一组嵌套列表

[英]How to print a set of nested list as I need in Python 3.6

I have a nested containing values of different lengths as so: 我有一个嵌套,其中包含不同长度的值,如下所示:

[['cat', 123, 'yellow'],
['dog', 12345, 'green'],
[horse', 123456, 'red']]

I want to print them like this: 我想这样打印它们:

cat,   123,    yellow
dog,   12345,  green
horse, 123456, red 

I have tried using pprint to achieve my aims with the following code: 我尝试使用pprint通过以下代码实现我的目标:

for sub in master_list:

    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(sub)

Where master is the nested list and sub the lists within it. 其中master是嵌套列表,子列表是其中的子列表。 This however gives me an output like so: 但是,这给了我这样的输出:

[
    'cat', 
    123, 
    'yellow'
],

[
    'dog', 
    12345, 
    'green'
],

[
    horse', 
    123456, 
    'red'
]

Is there a python module that allows me to relatively easily achieving what I want, without some sort of convoluted hack? 是否有一个python模块,可以让我相对容易地实现所需的功能,而无需进行复杂的修改?

Thanks 谢谢

You may use the following code: 您可以使用以下代码:

myLst = [['cat', 123, 'yellow'],
['dog', 12345, 'green'],
['horse', 123456, 'red']]

for subLst in myLst:
    print("\t".join([str(ele) for ele in subLst]))

Which is printing the output like so: 像这样打印输出:

cat    123      yellow
dog    12345    green
horse  123456   red

In case you want to have "," too, just change the line 如果您也想使用“,”,只需更改行

print("\t".join([str(ele) for ele in subLst]))

to

print(",\t".join([str(ele) for ele in subLst]))

And the complete thing as a one-liner: 和完整的一线工作:

print("\n".join([",\t".join([str(ele) for ele in subLst]) for subLst in myLst]))

Or in case you need a function: 或者,如果您需要一个功能:

def printLst(myLst):
    print("\n".join([",\t".join([str(ele) for ele in subLst]) for subLst in myLst]))

Edit 编辑

As pointed out in the comments this is also a good use-case for the python map function. 正如评论中指出的那样,这也是python map函数的一个很好的用例。 Which can be used in order to make everything shorter ;) 可以用来使所有内容变得更短;)

Pandas can help. 熊猫可以提供帮助。

import pandas as pd
lst = [['cat', 123, 'yellow'], ['dog', 12345, 'green'], ['horse', 123456, 'red']]
df = pd.DataFrame(lst)
print(df)

Output: 输出:

    0   1   2
0   cat     123     yellow
1   dog     12345   green
2   horse   123456  red

You can use this: 您可以使用此:

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

Output: 输出:

cat     123     yellow
dog     12345   green 
horse   123456  red

Your concrete format wishescan be solved by printing with ljust to add the needed spaces: 您的具体格式愿望可以通过使用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

Output: 输出:

cat,    123,    yellow
dog,    12345,  green
horse,  123456, red

Doku: 数独:


Generally for formatting you can use the string format mini language to format your output to your liking: 通常,对于格式化,您可以使用字符串格式迷你语言来按自己的喜好格式化输出:

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("")

Output: 输出:

cat      , 123      , yellow   
dog      , 12345    , green    
horse    , 123456   , red      

The format string "{:<{}} ".format(elem,max_len+2) formats element rightaligned into max_len+2 characters. 格式字符串"{:<{}} ".format(elem,max_len+2) element右对齐为max_len+2字符。 The first thing is just to make your , not appear on the start of the line. first件事就是使您的,而不出现在行的开头。

You can do this: 你可以这样做:

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()

Results: 结果:

cat,      123,      orange  
elephant, 500000,   green   
horse,    123456.0, red  

Explanations: 说明:

spacing is defined by first gathering the maximum lengths of each "column" in your data. 通过首先收集数据中每个“列”的最大长度来定义spacing We can group the columns by using: 我们可以使用以下方式对列进行分组:

zip(*data)

Which gives a transposed copy of your data like this: 这样可以得到数据的转置副本,如下所示:

('cat', 'elephant', 'horse'), 
(123, 500000, 123456.0), 
('orange', 'green', 'red')

Then we use the map function to apply the len(str(x)) function over these columns: 然后,我们使用map函数在这些列上应用len(str(x))函数:

(3, 8, 5),
(3, 6, 8), 
(6, 5, 3)

Then we just get the max of each column, combine everything in a list comprehension and return it as spacing : 然后,我们只获取每一列的max ,将所有内容组合成列表推导式,并将其返回为spacing

spacing = [max(map(lambda x: len(str(x)), d)) for d in zip(*data)]

Then, while we loop through your data, we want to also enumerate(row) so we know which "column" we're working with. 然后,当我们遍历您的数据时,我们还要enumerate(row)以便我们知道我们正在使用哪个“列”。 i will give you the index of the column in addition to the actual elem . 除了实际的elem i还将为您提供该列的索引。

After that, we assign a temporary str to append the comma if it's not the last element: 之后,如果不是最后一个元素,我们将分配一个临时str来附加逗号:

e = str(elem) + (',' if i < len(row) -1 else '')

This makes it a bit more readable then adding it as part of the format params. 这使得它更具可读性,然后将其添加为格式参数的一部分。

Afterwards we use string formatting (or e.ljust(spacing[i] + 1) if you wish) to add the predefined maximum spacing based on the column. 之后,我们使用字符串格式设置(或者e.ljust(spacing[i] + 1)需要使用e.ljust(spacing[i] + 1) )添加基于列的预定义最大spacing Note we format the string twice by first escaping the outer curly brackets ( {{ and }} ), so it can be in sequence: 请注意,我们通过先转义外部大括号( {{}} )来格式化字符串两次,因此它可以按顺序排列:

'{{:{}}}.format(9).format(e)
# becomes
'{:9}'.format(e)
# becomes
'cat,     '

Note the use of end='' to make the print line continuous until the row has finished. 请注意使用end=''使打印行连续直到row结束。 The spacing[i] + 1 is to account for the added comma. spacing[i] + 1用于说明添加的逗号。

I must confess this might not be the most efficient way, but depending on what you're trying to achieve the solution can be markedly different. 我必须承认,这可能不是最有效的方法,但是根据您要实现的解决方案而定,可能会有明显的不同。

Another way, given the nested list: 给定嵌套列表的另一种方法:

table = [['cat', 123, 'yellow'],
          ['dog', 12345, 'green'],
          ['horse', 123456, 'red']]

Using string methods: 使用字符串方法:

for line in table:
  print("|", end='')
  for word in line:
    print (f" {word}".ljust(10) + "|", end='')
  print()

To get: 要得到:

| cat      | 123      | yellow   |
| dog      | 12345    | green    |
| horse    | 123456   | red      |

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

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