program story

파이썬에서 "멋지게"목록을 인쇄하는 방법

inputbox 2020. 10. 28. 08:04
반응형

파이썬에서 "멋지게"목록을 인쇄하는 방법


PHP에서는 다음과 같이 할 수 있습니다.

echo '<pre>'
print_r($array);
echo '</pre>'

Python에서는 현재 다음과 같이합니다.

print the_list

그러나 이로 인해 엄청난 양의 데이터가 발생합니다. 읽을 수있는 트리로 멋지게 인쇄 할 수있는 방법이 있습니까? (들여 쓰기 포함)?


from pprint import pprint
pprint(the_list)

가져올 필요없이 작동하는 디버깅 중 빠른 해킹 pprint'\n'.

>>> lst = ['foo', 'bar', 'spam', 'egg']
>>> print '\n'.join(lst)
foo
bar
spam
egg

당신은 다음과 같은 것을 의미합니다 ... :

>>> print L
['this', 'is', 'a', ['and', 'a', 'sublist', 'too'], 'list', 'including', 'many', 'words', 'in', 'it']
>>> import pprint
>>> pprint.pprint(L)
['this',
 'is',
 'a',
 ['and', 'a', 'sublist', 'too'],
 'list',
 'including',
 'many',
 'words',
 'in',
 'it']
>>> 

...? 간단한 설명에서 가장 먼저 떠오르는 것은 표준 라이브러리 모듈 pprint 입니다. 그러나 예제 입력 및 출력을 설명 할 수 있다면 (당신을 돕기 위해 PHP를 배울 필요가 없습니다 ;-), 우리가 더 구체적인 도움을 제공 할 수 있습니다!


인쇄 함수 인수의 목록을 "압축 해제"하고 구분 기호로 줄 바꿈 (\ n)을 사용하면됩니다.

print (* lst, sep = '\ n')

lst = ['foo', 'bar', 'spam', 'egg']
print(*lst, sep='\n')

foo
bar
spam
egg

import json
some_list = ['one', 'two', 'three', 'four']
print(json.dumps(some_list, indent=4))

산출:

[
    "one",
    "two",
    "three",
    "four"
]

https://docs.python.org/3/library/pprint.html

텍스트가 필요한 경우 (예 : curses와 함께 사용) :

import pprint

myObject = []

myText = pprint.pformat(myObject)

그런 다음 myText변수는 php var_dump또는 print_r. 더 많은 옵션, 인수는 문서를 확인하십시오.


다른 답변에서 알 수 있듯이 pprint 모듈이 트릭을 수행합니다.
그럼에도 불구하고 전체 목록을 일부 로그 파일에 넣어야하는 디버깅의 경우 pprint와 함께 모듈 로깅 과 함께 pformat 메서드를 사용해야 할 수 있습니다 .

import logging
from pprint import pformat

logger = logging.getLogger('newlogger')
handler = logging.FileHandler('newlogger.log')

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)

logger.addHandler(handler) 
logger.setLevel(logging.WARNING)

data = [ (i, { '1':'one',
           '2':'two',
           '3':'three',
           '4':'four',
           '5':'five',
           '6':'six',
           '7':'seven',
           '8':'eight',
           })
         for i in xrange(3)
      ]

logger.error(pformat(data))

파일에 직접 기록해야하는 경우 stream 키워드를 사용하여 출력 스트림을 지정해야합니다. Ref

from pprint import pprint

with open('output.txt', 'wt') as out:
   pprint(myTree, stream=out)

참조 스테파노 대해 Sanfilippo의 답변을


As other answers have mentioned, pprint is a great module that will do what you want. However if you don't want to import it and just want to print debugging output during development, you can approximate its output.

Some of the other answers work fine for strings, but if you try them with a class object it will give you the error TypeError: sequence item 0: expected string, instance found.

For more complex objects, make sure the class has a __repr__ method that prints the property information you want:

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __repr__(self):
        return "Foo - (%r)" % self.bar

And then when you want to print the output, simply map your list to the str function like this:

l = [Foo(10), Foo(20), Foo("A string"), Foo(2.4)]
print "[%s]" % ",\n ".join(map(str,l))

outputs:

 [Foo - (10),
  Foo - (20),
  Foo - ('A string'),
  Foo - (2.4)]

You can also do things like override the __repr__ method of list to get a form of nested pretty printing:

class my_list(list):
    def __repr__(self):
        return "[%s]" % ",\n ".join(map(str, self))

a = my_list(["first", 2, my_list(["another", "list", "here"]), "last"])
print a

gives

[first,
 2,
 [another,
 list,
 here],
 last]

Unfortunately no second-level indentation but for a quick debug it can be useful.


For Python 3, I do the same kind of thing as shxfee's answer:

def print_list(my_list):
    print('\n'.join(my_list))

a = ['foo', 'bar', 'baz']
print_list(a)

which outputs

foo
bar
baz

As an aside, I use a similar helper function to quickly see columns in a pandas DataFrame

def print_cols(df):
    print('\n'.join(df.columns))

you can also loop trough your list:

def fun():
  for i in x:
    print(i)

x = ["1",1,"a",8]
fun()

참고URL : https://stackoverflow.com/questions/1523660/how-to-print-a-list-in-python-nicely

반응형