Перейти к содержимому

Как красиво вывести список python

  • автор:

Python: советы, уловки, хаки (часть 1)

Хотите писать более лаконичный и читаемый код? Вы хотите уместить как можно больше смысла в одно выражение? Считаете, что прочитать о нескольких уловках лучше, чем провести остаток жизни за чтением документации? Вы обратились по адресу. Мы начнем с маленьких уловок, которые вы уже могли встретить, если немного работали с Python. Но я обещаю, что ближе к концу статьи вас ожидает больше безумных вещей.

Содержание

1. Маленькие уловки. Четыре типа кавычек. Правдивость различных объектов. Проверка на вхождение подстроки. Красивый вывод списка. Целочисленное деление и деление с плавающей точкой. Лямбда-функции.
2. Списки. Генераторы списков и выражения-генераторы.

Я старался сделать, чтобы все фрагменты кода запускались без дополнительных изменений. Если хотите, можете скопировать их в оболочку Python и посмотреть, что получится. Обратите внимание, что многие примеры содержат «неправильные» фрагменты, которые закомментированы. Ничто вам не мешает раскомментировать строку и посмотреть, что произойдет.

Небольшое разграничение между true и True в этой статье: когда я говорю, что объект true, это значит, что будучи приведенным к типу boolean, он становится True. Аналогично с false и False.

1 Маленькие уловки
1.1 Четыре типа кавычек

Начнем с того, что вы, возможно, уже знаете. В некоторых языках программирования одинарные и двойные кавычки предназначены для разных вещей. Python позволяет использовать оба варианта (но строка должна начинаться и заканчиваться одним и тем же типом кавычек). В Python также есть еще два типа кавычек: »’ (тройные одинарные) и «»» (тройные двойные). Таким образом, можно использовать несколько уровней кавычек, прежде чем придется заботиться об их экранировании. Например, этот код правильный:

1.2 Правдивость различных объектов

В отличие от некоторых языков программирования, в Python объект считается false, только если он пуст. Это значит, что не нужно проверять длину строки, кортежа или словаря — достаточно проверить его как логическое выражение.

Легко предсказать, что 0 — тоже false, а остальные числа — true.

Например, следующие выражения эквивалентны. В данном случае my_object — строка, но здесь мог оказаться другой тип (с соответствующими изменениями условий блока if).

Итак, нет необходимости проверять длину объекта, если вас интересует только, пуст он или нет.

1.3 Проверка на вхождение подстроки

Это маленькая, довольно очевидная подсказка, но я узнал о ней лишь через год изучения Python. Должно быть, вы знаете, что можно проверить, содержится ли нужный элемент в кортеже, списке, словаре, с помощью конструкции ‘item in list’ или ‘item not in list’. Я не мог представить, что это сработает для строк. Я всегда писал что-то вроде этого:

Этот код довольно неуклюжий. Совершенно так же работает ‘if substring in string’:

Проще и понятней. Может быть, очевидно для 99% людей, но мне хотелось бы узнать об этом раньше, чем я узнал.

1.4 Красивый вывод списка

Обычный формат вывода списка с помощью print не очень удобен. Конечно, становится понятно, что из себя представляет список, но чаще всего пользователь не хочет видеть кавычки вокруг каждого элемента. Есть простое решение, использующее метод join строки:

Метод join преобразовывает список в строку, рассматривая каждый элемент как строку. Разделителем является та строка, для которой был вызван join. Он достаточно умен, чтобы не вставлять разделитель после последнего элемента.

Дополнительный бонус: join работает линейное время. Никогда не создавайте строку складыванием элементов списка в цикле for: это не просто некрасиво, это занимает квадратичное время!

1.5 Целочисленное деление и деление с плавающей точкой

Если вы делите целое число на целое, по умолчанию результат обрезается до целого. Например, 5/2 вернет 2.

Есть два способа это исправить. Первый и самый простой способ заключается в том, чтобы преобразовать одно из чисел к типу float. Для констант достаточно добавить «.0» к одному из чисел: 5.0/2 вернет 2.5. Также вы можете использовать конструкцию float(5)/2.

Второй способ дает более чистый код, но вы должны убедиться, что ваша программа не сломается от этого существенного изменения. После вызова ‘from __future__ import division’ Python всегда будет возвращать в качестве результата деления float. Если вам понадобится целочисленное деление, используйте оператор //: 5//2 всегда возвращает 2.

В одной из следующих версий Python такое поведение станет дефолтным. Если вы хотите, чтобы ваш код оставался совместимым, используйте оператор // для целочисленного деления, даже если вы не используете этот импорт.

1.6 Лямбда-функции

Иногда нужно передать функцию в качестве аргумента или сделать короткую, но сложную операцию несколько раз. Можно определить функцию обычным способом, а можно использовать лямбда-функцию — маленькую функцию, возвращающую результат одного выражения. Следующие два определения полностью идентичны:

Преимущество лямбда-функции в том, что она является выражением и может быть использована внутри другого выражения. Ниже приведен пример, использующий функцию map, которая вызывает функцию для каждого элемента списка и возвращает список результатов. (В следующем пункте я покажу, что map практически бесполезен. Но он дает нам возможность привести хороший пример в одну строку.)

Без лямбда-функций нам пришлось бы определить функцию отдельно. Мы просто сэкономили одну строку кода и одно имя переменной.

2 Списки
2.1 Генераторы списков

Если вы использовали Python достаточно долго, вы должны были хотя бы слышать о понятии «list comprehensions». Это способ уместить цикл for, блок if и присваивание в одну строку.
Другими словами, вы можете отображать (map) и фильтровать списки одним выражением.

2.1.1 Отображение списка

Начнем с простейшего примера. Допустим, нам надо возвести в квадрат все элементы списка. Свежеиспеченный программист на Python может написать код вроде этого:

Мы «отобразили» один список на другой. Это также можно сделать с помощью функции map:

Этот код определенно короче (одна строка вместо трех), но всё еще некрасив. С первого взгляда сложно сказать, что делает функция map (она принимает в качестве аргументов функцию и список и применяет функцию к каждому элементу списка). К тому же мы вынуждены определять функцию, это выглядит довольно беспорядочно. Если бы только существовал более красивый путь… например, генератор списка:

Этот код делает абсолютно то же самое, но он короче, чем первый пример, и понятней, чем второй. Человек без проблем определит, что делает код, для этого даже не обязательно знать Python.

2.1.2 Фильтрация списка

А что, если нас интересует фильтрация списка? Например, требуется удалить элементы, большие или равные 4. (Да, примеры не очень реалистичны. Как бы то ни было. )

Новичок напишет так:

Очень просто, не так ли? Но код занимает 4 строки, содержит два уровня отступов и при этом делает тривиальную вещь. Можно уменьшить размер кода с помощью функции filter:

Аналогично функции map, о которой мы говорили выше, filter сокращает код, но выглядит довольно уродливо. Что, черт возьми, происходит? Как и map, filter получает функцию и список. Если функция от элемента возвращает true, элемент включается в результирующий список. Разумеется, мы можем сделать это через генератор списка:

Снова мы получили более короткий, ясный и понятный код.

2.1.3 Одновременное использование map и filter

Теперь мы можем использовать всю силу генератора списков. Если я вас еще не убедил, что map и filter тратят слишком много вашего времени, надеюсь, теперь вы со мной согласитесь.

Пусть требуется отобразить и отфильтровать список одновременно. Другими словами, я хочу увидеть квадраты элементов списка, меньших 4. Еще раз, неофит напишет так:

Увы, код начал растягиваться вправо. Может, получится упростить его? Попробуем использовать map и filter, но у меня плохое предчувствие…

Раньше map и filter было трудно читать, теперь — невозможно. Очевидно, это не лучшая идея. И снова генератор списков спасает ситуацию:

Получилось немного длиннее, чем предыдущие примеры с генератором списков, но, по моему мнению, вполне читабельно. Определенно лучше, чем цикл for или использование map и filter.

Как вы видите, генератор списков сначала фильтрует, а затем отображает. Если вам обязательно нужно наоборот, получится сложнее. Придется использовать либо вложенные генерации, либо map и filter, либо обычный цикл for, в зависимости от того, что проще. Но это уже выходит за рамки статьи.

2.1.4 Выражения-генераторы

Существует обратная сторона генератора списков: весь список должен находиться в памяти. Это не проблема для маленьких списков, как в предыдущих примерах, и даже на несколько порядков больше. Но в конце концов это становится неэффективным.

Выражения-генераторы (Generator Expressions) появились в Python 2.4. Из всех фишек Python им уделяется, наверно, меньше всего внимания. Отличие их от генераторов списков состоит в том, что они не загружают в память список целиком, а создают ‘generator object’, и в каждый момент загружен только один элемент списка.

Конечно, если вы хотите использовать список для чего-нибудь, это не особо поможет. Но если вы просто передаете его куда-нибудь, где нужен любой итерируемый объект (цикл for, например), стоит использовать функцию генератора.

Выражения-генераторы имеют такой же синтаксис, как генераторы списков, но вместо квадратных скобок используются круглые:

Это более эффективно, чем использование генератора списков.

Итак, имеет смысл использовать выражения-генераторы для списков больших размеров. Если весь список целиком нужен вам для какой-то другой цели, то можно использовать любой из вариантов. Но использовать выражения-генераторы — хорошая привычка, если нет аргументов против этого. Правда, не надейтесь увидеть ускорение работы, если список небольшой.

В качестве финального штриха хочу заметить, что выражения-генераторы достаточно заключить в одни круглые скобки. Например, в случае, если вы вызываете функцию с одним аргументом, можно писать так: some_function(item for item in list).

2.1.5 Заключение

Мне не хочется этого говорить, но мы только прикоснулись к тому, что можно делать с помощью выражений-генераторов и генераторов списков. Здесь можно использовать всю силу for и if, а также оперировать с чем угодно, лишь бы оно было итерируемым объектом.

Prettify Your Data Structures With Pretty Print in Python

Dealing with data is essential for any Pythonista, but sometimes that data is just not very pretty. Computers don’t care about formatting, but without good formatting, humans may find something hard to read. The output isn’t pretty when you use print() on large dictionaries or long lists—it’s efficient, but not pretty.

The pprint module in Python is a utility module that you can use to print data structures in a readable, pretty way. It’s a part of the standard library that’s especially useful for debugging code dealing with API requests, large JSON files, and data in general.

By the end of this tutorial, you’ll:

  • Understand why the pprint module is necessary
  • Learn how to use pprint() , PrettyPrinter , and their parameters
  • Be able to create your own instance of PrettyPrinter
  • Save formatted string output instead of printing it
  • Print and recognize recursive data structures

Along the way, you’ll also see an HTTP request to a public API and JSON parsing in action.

Free Bonus: Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Understanding the Need for Python’s Pretty Print

The Python pprint module is helpful in many situations. It comes in handy when making API requests, dealing with JSON files, or handling complicated and nested data. You’ll probably find that using the normal print() function isn’t adequate to efficiently explore your data and debug your application. When you use print() with dictionaries and lists, the output doesn’t contain any newlines.

Before you start exploring pprint , you’ll first use urllib to make a request to get some data. You’ll make a request to Placeholder for some mock user information. The first thing to do is to make the HTTP GET request and put the response into a dictionary:

Here, you make a basic GET request and then parse the response into a dictionary with json.loads() . With the dictionary now in a variable, a common next step is to print the contents with print() :

Oh dear! One huge line with no newlines. Depending on your console settings, this might appear as one very long line. Alternatively, your console output might have its word-wrapping mode on, which is the most common situation. Unfortunately, that doesn’t make the output much friendlier!

If you look at the first and last characters, you can see that this appears to be a list. You might be tempted to start writing a loop to print the items:

This for loop would print each object on a separate line, but even then, each object takes up way more space than can fit on a single line. Printing in this way does make things a bit better, but it’s by no means ideal. The above example is a relatively simple data structure, but what would you do with a deeply nested dictionary 100 times the size?

Sure, you could write a function that uses recursion to find a way to print everything. Unfortunately, you’ll likely run into some edge cases where this won’t work. You might even find yourself writing a whole module of functions just to get to grips with the structure of the data!

Enter the pprint module!

Working With pprint

pprint is a Python module made to print data structures in a pretty way. It has long been part of the Python standard library, so installing it separately isn’t necessary. All you need to do is to import its pprint() function:

Then, instead of going with the normal print(users) approach as you did in the example above, you can call your new favorite function to make the output pretty:

This function prints users —but in a new-and-improved pretty way:

How pretty! The keys of the dictionaries are even visually indented! This output makes it so much more straightforward to scan and visually analyze data structures.

Note: The output you’ll see will be longer if you run the code yourself. This code block truncates the output for readability.

If you’re a fan of typing as little as possible, then you’ll be pleased to know that pprint() has an alias, pp() :

pp() is just a wrapper around pprint() , and it’ll behave exactly the same way.

Note: Python has included this alias since version 3.8.0 alpha 2.

However, even the default output may be too much information to scan at first. Maybe all you really want is to verify that you’re dealing with a list of plain objects. For that, you’ll want to tweak the output a little.

For these situations, there are various parameters you can pass to pprint() to make even the tersest data structures pretty.

Exploring Optional Parameters of pprint()

In this section, you’ll learn about all the parameters available for pprint() . There are seven parameters that you can use to configure your Pythonic pretty printer. You don’t need to use them all, and some will be more useful than others. The one you’ll find most valuable will probably be depth .

Summarizing Your Data: depth

One of the handiest parameters to play around with is depth . The following Python command will only print the full contents of users if the data structure is at or lower than the specified depth—all while keeping things pretty, of course. The contents of deeper data structures are replaced with three dots:

Now you can immediately see that this is indeed a list of dictionaries. To explore the data structure further, you can increase the depth by one level, which will print all the top-level keys of the dictionaries in users :

Now you can quickly check whether all the dictionaries share their top-level keys. This is a valuable observation to make, especially if you’re tasked with developing an application that consumes data like this.

Giving Your Data Space: indent

The indent parameter controls how indented each level of the pretty-printed representation will be in the output. The default indent is just 1 , which translates to one space character:

The most important part of the indenting behavior of pprint() is keeping all the keys aligned visually. How much indentation is applied depends on both the indent parameter and where the key is.

Since there’s no nesting in the examples above, the amount of indentation is based completely on the indent parameter. In both examples, note how the opening curly bracket ( < ) is counted as a unit of indentation for the first key. In the first example, the opening single quote for the first key comes right after < without any spaces in between because the indent is set to 1 .

When there is nesting, however, the indentation is applied to the first element in-line, and pprint() then keeps all following elements aligned with the first one. So if you set your indent to 4 when printing users , the first element will be indented by four characters, while the nested elements will be indented by more than eight characters because the indentation starts from the end of the first key:

This is just another part of the pretty in Python’s pprint() !

Limiting Your Line Lengths: width

By default, pprint() will only output up to eighty characters per line. You can customize this value by passing in a width argument. pprint() will make an effort to fit the contents on one line. If the contents of a data structure go over this limit, then it’ll print every element of the current data structure on a new line:

When you leave the width at the default of eighty characters, the dictionary at users[0][‘address’][‘geo’] only contains a ‘lat’ and a ‘lng’ attribute. This means that taking the sum of the indent and the number of characters needed to print out the dictionary, including the spaces in between, comes to less than eighty characters. Since it’s less than eighty characters, the default width, pprint() puts it all on one line.

However, the dictionary at users[0][‘company’] would go over the default width, so pprint() puts each key on a new line. This is true of dictionaries, lists, tuples, and sets:

If you set the width to a large value like 160 , then all the nested dictionaries fit on one line. You can even take it to extremes and use a huge value like 500 , which, for this example, prints the whole dictionary on one line:

Here, you get the effects of setting width to a relatively large value. You can go the other way and set width to a low value such as 1 . However, the main effect that this will have is making sure every data structure will display its components on separate lines. You’ll still get the visual indentation that lines up the components:

It’s hard to get Python’s pprint() to print ugly. It’ll do everything it can to be pretty!

In this example, on top of learning about width , you’re also exploring how the printer splits up long lines of text. Note how users[0][«company»][«catchPhrase»] , which was initially ‘Multi-layered client-server neural-net’ , has been split on each space. The printer avoids dividing this string mid-word because that would make it hard to read.

Squeezing Your Long Sequences: compact

You might think that compact refers to the behavior you explored in the section about width —that is, whether compact makes data structures appear on one line or separate lines. However, compact only affects the output once a line goes over the width .

Note: compact only affects the output of sequences: lists, sets, and tuples, and not dictionaries. This is intentional, though it’s not clear why this decision was taken. There’s an ongoing discussion about that in Python Issue #34798.

If compact is True , then the output will wrap onto the next line. The default behavior is for each element to appear on its own line if the data structure is longer than the width:

Pretty-printing this list using the default settings prints out the abbreviated version on one line. Limiting width to 40 characters, you force pprint() to output all the list’s elements on separate lines. If you then set compact=True , then the list will wrap at forty characters and be more compact than it would typically look.

Note: Beware that setting the width to less than seven characters— which, in this case, is equivalent to the [<. >, output— seems to bypass the depth argument completely, and pprint() ends up printing everything without any folding. This has been reported as bug #45611.

compact is useful for long sequences with short elements that would otherwise take up many lines and make the output less readable.

Directing Your Output: stream

The stream parameter refers to the output of pprint() . By default, it goes to the same place that print() goes to. Specifically, it goes to sys.stdout , which is actually a file object in Python. However, you can redirect this to any file object, just like you can with print() :

Here you create a file object with open() , and then you set the stream parameter in pprint() to that file object. If you then open the output.txt file, you should see that you’ve pretty-printed everything in users there.

Python does have its own logging module. However, you can also use pprint() to send pretty outputs to files and have these act as logs if you prefer.

Preventing Dictionary Sorting: sort_dicts

Although dictionaries are generally considered unordered data structures, since Python 3.6, dictionaries are ordered by insertion.

pprint() orders the keys alphabetically for printing:

Unless you set sort_dicts to False , Python’s pprint() sorts the keys alphabetically. It keeps the output for dictionaries consistent, readable, and—well—pretty!

When pprint() was first implemented, dictionaries were unordered. Without alphabetically ordering the keys, a dictionary’s keys could have theoretically differed at each print.

Prettifying Your Numbers: underscore_numbers

The underscore_numbers parameter is a feature introduced in Python 3.10 that makes long numbers more readable. Considering that the example you’ve been using so far doesn’t contain any long numbers, you’ll need a new example to try it out:

If you tried running this call to pprint() and got an error, you’re not alone. As of October 2021, this argument doesn’t work when calling pprint() directly. The Python community noticed this quickly, and it’s been fixed in the December 2021 3.10.1 bugfix release. The folks at Python care about their pretty printer! They’ll probably have fixed this by the time you’re reading this tutorial.

If underscore_numbers doesn’t work when you call pprint() directly and you really want pretty numbers, there is a workaround: When you create your own PrettyPrinter object, this parameter should work just like it does in the example above.

Next, you’ll cover how to create a PrettyPrinter object.

Creating a Custom PrettyPrinter Object

It’s possible to create an instance of PrettyPrinter that has defaults you’ve defined. Once you have this new instance of your custom PrettyPrinter object, you can use it by calling the .pprint() method on the PrettyPrinter instance:

With these commands, you:

  • Imported PrettyPrinter , which is a class definition
  • Created a new instance of that class with certain parameters
  • Printed the first user in users
  • Defined a list of a couple of long numbers
  • Printed number_list , which also demonstrates underscore_numbers in action

Note that the arguments you passed to PrettyPrinter are exactly the same as the default pprint() arguments, except that you skipped the first parameter. In pprint() , this is the object you want to print.

This way, you can have various printer presets—perhaps some going to different streams—and call them when you need them.

Getting a Pretty String With pformat()

What if you don’t want to send the pretty output of pprint() to a stream? Perhaps you want to do some regex matching and replace certain keys. For plain dictionaries, you might find yourself wanting to remove the brackets and quotes to make them look even more human-readable.

Whatever it is that you might want to do with the string pre-output, you can get the string by using pformat() :

pformat() is a tool you can use to get between the pretty printer and the output stream.

Another use case for this might be if you’re building an API and want to send a pretty string representation of the JSON string. Your end users would probably appreciate it!

Handling Recursive Data Structures

Python’s pprint() is recursive, meaning it’ll pretty-print all the contents of a dictionary, all the contents of any child dictionaries, and so on.

Ask yourself what happens when a recursive function runs into a recursive data structure. Imagine that you have dictionary A and dictionary B :

  • A has one attribute, .link , which points to B .
  • B has one attribute, .link , which points to A .

If your imaginary recursive function has no way to handle this circular reference, it’ll never finish printing! It would print A and then its child, B . But B also has A as a child, so it would go on into infinity.

Luckily, both the normal print() function and the pprint() function handle this gracefully:

While Python’s regular print() just abbreviates the output, pprint() explicitly notifies you of recursion and also adds the ID of the dictionary.

If you want to explore why this structure is recursive, you can learn more about passing by reference.

Conclusion

You’ve explored the primary usage of the pprint module in Python and some ways to work with pprint() and PrettyPrinter . You’ll find that pprint() is especially handy whenever you’re developing something that deals with complex data structures. Maybe you’re developing an application that uses an unfamiliar API. Perhaps you have a data warehouse full of deeply-nested JSON files. These are all situations where pprint can come in handy.

In this tutorial, you’ve learned how to:

  • Import pprint for use in your programs
  • Use pprint() in place of the regular print()
  • Understand all the parameters you can use to customize your pretty-printed output
  • Get the formatted output as a string before printing it
  • Create a custom instance of PrettyPrinter
  • Recognize recursive data structures and how pprint() handles them

To help you get to grips with the function and parameters, you used an example of a data structure representing some users. You also explored some situations where you might use pprint() .

Congratulations! You’re now better equipped to deal with complex data by using Python’s pprint module.

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Ian Currie

Ian is a Python nerd who uses it for everything from tinkering to helping people and companies manage their day-to-day and develop their businesses.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Bartosz Zaczyński

Martin Breuss

Sadie Parker

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Распечатать список Python Красиво [Нажмите и запустить код]

Как распечатать список Python в красивом и полностью настраиваемом способе? Эта статья показывает вам шесть эффективных способов сделать это. Изучая эти альтернативы, вы не только узнаете, как печатать список в Python, вы станете лучшим кодером в целом. Если вы просто хотите узнать лучший способ печатать … Распечатать список Python Красиво [Нажмите и запустить код] Подробнее »

  • Автор записи

Как распечатать список Python в красивом и полностью настраиваемом способе?

Эта статья показывает вам шесть эффективных способов сделать это. Изучая эти альтернативы, вы не только узнаете, как печатать список в Python, вы станете лучшим кодером в целом.

Если вы просто хотите узнать лучший способ распечатать список в Python, вот короткий ответ:

  • Пройти список как вход в Распечатать() Функция в Python.
  • ИспользоватьОператор Звездочки * Перед списком, чтобы «распаковать» список в функцию печати.
  • Использовать сент Аргумент, чтобы определить, как отделить два элемента списка визуально.

Попробуйте сами в нашем интерактивном коде раковину:

Это лучший и самый пифитонический способ печатать список Python. Если вы все еще хотите узнать об альтернативах – и улучшить свои навыки Python в процессе выполнения так-чтения!

Метод 1: Используйте оператор Print () по умолчанию ()

По умолчанию Печать () Заявление преобразует список в строковое представление, которое включает элементы списка в квадратных скобках [ и ] и отделяет два последующих элемента с запятой и пустым пространством A, B Отказ Это стандартное представление списка.

Легко читать и писать Не настраивается
Быстрый
Краткий

Попробуйте сами в нашем интерактивном коде раковину:

Следующий метод преодолевает основной недостаток не очень настраиваемого.

Способ 2: Итера В Для петли

Если вы хотите полный контроль о выходе каждого элемента каждого списка, вы можете использовать простой подход к использованию цикла для петли для повторения каждого элемента X в списке. Затем вы можете решить для себя, как распечатать каждый элемент.

Полностью настраиваемый Относительно медленно
Простой Менее лаконично
Новая линия после каждого элемента

Попробуйте сами в нашей интерактивной Python Shell:

Способ 3: Итерации для цикла с концом аргументации

Если вы предпочитаете распечатать все элементы в одну строку, разделенную тремя символами пробелов, вы можете сделать это, определив конец Аргумент Печать () Функция, которая определяет, какой символ добавляется после каждого элемента, который был напечатан к оболочке (по умолчанию: New-Line Charease \ N ):

Вы видите, что конец Аргумент перезаписывает поведение по умолчанию печати нового стилового символа в конце каждого элемента. Вместо этого каждые два элемента разделены тремя пустыми пробелами.

Полностью настраиваемый Относительно медленно
Простой Менее лаконично

Попробуйте сами в нашем интерактивном коде раковину:

Давайте преодолеваем недостаток для петли меньшей кражи!

Метод 4: распаковка с аргументом сепаратора

Печать () Функция работает с утечкой в качестве ввода. Вы можете использовать Звездочный оператор * Перед списком, чтобы «распаковать» список в функцию печати. Теперь вы можете использовать Сен Аргумент Печать () Функция для определения того, как отделить два элемента потенциала.

Сен Аргумент позволяет точно определить то, что поставить между каждой парой элементов в итерателе. Это позволяет вам полную настройку и сохраняет код наклониться и кратко.

Полностью настраиваемый Сложнее читать для начинающих
Быстрый
Краткий

Попробуйте сами в нашем интерактивном коде раковину:

Это лучший и самый пифитонический способ печатать список Python. Если вы все еще хотите узнать о вариантах, продолжайте прочитать.

Способ 5: Используйте метод String.join ()

String.join (ИТЕРАЛ) Метод объединяет все элементы в ИТЕРИТЕЛЬНО , используя строка в качестве сепаратора между двумя элементами. Таким образом, это работает точно так же, как Сен Аргумент Печать () функция.

Обратите внимание, что вы можете использовать только эти методы, если элементы списка уже строки. Если они целые числа, присоединяясь к ним вместе не работает, и Python бросает ошибку:

Полностью настраиваемый Сложнее читать для начинающих
Краткий Медленный
Работает только для струнных элементов

Попробуйте сами в нашем интерактивном коде раковину:

Так как вы применяете этот метод целочисленным спискам?

Метод 6: Используйте метод String.join () с картой ()

String.join (ИТЕРАЛ) Метод объединяет все элементы в ИТЕРИТЕЛЬНО , используя строка в качестве сепаратора между двумя элементами. Но ожидает, что все элементы в ИТЕРИТЕЛЬНО уже строки. Если они нет, вам нужно сначала преобразовать их. Для достижения этого вы можете использовать Встроенная карта () Метод в Python 3.x.

карта (ул, lst) Метод применяет функцию ул (х) каждому элементу х в списке. Другими словами, он преобразует каждый целочисленный элемент в строку. Альтернативный путь без карта (ул, lst) Функция будет Понимание списка [str (x) для x в lst] что приводит к тому же выходу.

Полностью настраиваемый Сложнее читать для начинающих
Краткий Медленный
Работает для всех типов данных

Попробуйте сами в нашем интерактивном коде раковину:

Итак, давайте закончим это!

Куда пойти отсюда?

Достаточно теории, давайте познакомимся!

Чтобы стать успешным в кодировке, вам нужно выйти туда и решать реальные проблемы для реальных людей. Вот как вы можете легко стать шестифункциональным тренером. И вот как вы польские навыки, которые вам действительно нужны на практике. В конце концов, что такое использование теории обучения, что никто никогда не нуждается?

Практические проекты – это то, как вы обостряете вашу пилу в кодировке!

Вы хотите стать мастером кода, сосредоточившись на практических кодовых проектах, которые фактически зарабатывают вам деньги и решают проблемы для людей?

Затем станьте питоном независимым разработчиком! Это лучший способ приближения к задаче улучшения ваших навыков Python – даже если вы являетесь полным новичком.

Присоединяйтесь к моему бесплатным вебинаре «Как создать свой навык высокого дохода Python» и посмотреть, как я вырос на моем кодированном бизнесе в Интернете и как вы можете, слишком от комфорта вашего собственного дома.

Присоединяйтесь к свободному вебинару сейчас!

Работая в качестве исследователя в распределенных системах, доктор Кристиан Майер нашел свою любовь к учению студентов компьютерных наук.

Чтобы помочь студентам достичь более высоких уровней успеха Python, он основал сайт программирования образования Finxter.com Отказ Он автор популярной книги программирования Python одноклассники (Nostarch 2020), Coauthor of Кофе-брейк Python Серия самооставленных книг, энтузиаста компьютерных наук, Фрилансера и владелец одного из лучших 10 крупнейших Питон блоги по всему миру.

Его страсти пишут, чтение и кодирование. Но его величайшая страсть состоит в том, чтобы служить стремлению кодер через Finxter и помогать им повысить свои навыки. Вы можете присоединиться к его бесплатной академии электронной почты здесь.

How to print a list in Python "nicely"

However, this will cause a big jumbo of data. Is there any way to print it nicely into a readable tree? (with indents)?

mechanical_meat's user avatar

11 Answers 11

John La Rooy's user avatar

Simply by «unpacking» the list in the print function argument and using a newline (\n) as separator.

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

A quick hack while debugging that works without having to import pprint would be to join the list on ‘\n’ .

You mean something like.

. From your cursory description, standard library module pprint is the first thing that comes to mind; however, if you can describe example inputs and outputs (so that one doesn’t have to learn PHP in order to help you;-), it may be possible for us to offer more specific help!

If you need the text (for using with curses for example):

Then myText variable will something alike php var_dump or print_r . Check the documentation for more options, arguments.

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

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

aaronpenne's user avatar

As the other answers suggest pprint module does the trick.
Nonetheless, in case of debugging where you might need to put the entire list into some log file, one might have to use pformat method along with module logging along with pprint.

And if you need to directly log it to a File, one would have to specify an output stream, using the stream keyword. Ref

El_Diablo's user avatar

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:

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

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

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *