Python — вывести список без пробелов и скобок
то при попытке вывести его в консоль обычным методом print(list) мы получим:
А вот что бы вывести значение списка без пробелов и скобок используем решение:
Как видите — все просто
И да — в случае возникновения вопросов пишите на почту, или в Telegram.
UPD: интересная мысль только что возникла — добавлять к каждой записи список поисковых запросов, по которым люди заходили на эту самую запись
Поисковые запросы:
как в питоне вывести список без квадратных скобок
как вывести список без скобок python
как вывести массив без скобок python
How to print a Numpy array without brackets?
I want to convert a = [1,2,3,4,5] into a_string = «1 2 3 4 5» . The real numpy array is quite big (50000×200) so I assume using for loops is too slow.
7 Answers 7
You can use the join method from string:
np.savetxt
Control the precision
Get a string instead of printing
We use latin1 because the docs tell us that it is the default encoding used.
All in one line
Or if you really want all in one line:
TODO: there is a trailing space. The only solution I see is to save to a string and strip.
Tested on Python 2.7.15rc1 and Python 3.6.6, numpy 1.13.3
![]()
Maybe a bit hacky, but I just slice them off after using np.array2string so:
np.array2string has lots of options also, so you can set your column width which can be very helpful with lots of data:
And it will smartly split at the array elements. Note the space appended to the beginning of the string to account for aligning the first row after removing the initial bracket.
Как напечатать массив Numpy без скобок?
Я хочу преобразовать a = [1,2,3,4,5] в a_string = «1 2 3 4 5» . Реальный массив numpy довольно большой (50000×200), поэтому я предполагаю, что использование for loops слишком медленное.
4 ответа
Вы можете использовать метод join из строки:
np.savetxt
Или, если массив инвертирован:
Или, если вам действительно нужна строка:
Вы можете контролировать точность с помощью fmt , чтобы получить:
Протестировано на Python 2.7.12, numpy 1.11.1.
Если у вас есть массив numpy, а не список (так как вы упоминаете «реальный массив numpy» в своем сообщении), вы можете использовать re.sub в строчном представлении массива
Опять же, это предполагает, что ваш массив a был в несколько раз массивным массивом. Это также имеет преимущество в работе над матрицами.
Numpy предоставляет две функции для этого array_str и array_repr — любой из них должен соответствовать вашим потребностям. Так как вы можете использовать любой из них, вот пример каждого из них:
Эти две функции очень оптимизированы и, как таковые, должны быть предпочтительнее функции, которую вы могли бы написать самостоятельно. Имея дело с массивами такого размера, я бы предположил, что вам нужна вся скорость, которую вы можете получить.
How to print list without brackets and quotes in Python.
In this article, we will figure out four unique methods to print list without brackets and quotes in Python but foremost, what is list?
A list is the data structure in python that allows you to store a collection of items stored in a variable. Lists are mutable or changeable. We can define a list with the following syntax.
The above line defines the list of different types of apples stored in the “apples” variable. It will give us the output like this:
![]()
But what if you want to display it by removing brackets and commas from list? Well, in this article we’re going to discuss different methods to do so.
Table of Contents
Using for loop:
For Loop is the most general solution that comes first to the mind when you try to solve this problem. In this, we iterate through each value of a list and print that value.
![]()
- First, we declare the list.
- Using for loop, we iterate through each value of a list and print that value with a comma and space. (if you only want to add a space between the values of a string then just add a space in the end parameter and skip the next steps).
- The for loop also added a comma and space at last so to remove this we move over the cursor to the last two printed items.
- Furthermore, at the last step, we move the comma with space.
Using join() method:
There is a built-in method in python called join(). It takes an iterable and converts it into a string with the specified value given with it.
![]()
You can define that value in the separator variable through which you want to join the items in the list.
One thing to remember that if you want to join the integer values, then the join method will not work because it is a string method. It will generate the following error.
![]()
But, if you want to use join function for print list without brackets and commas, then you can accomplish this by using map() function.
![]()
The map() function takes two argument, first is a function and second is a item from iterable which need to be mapped and it passes to that function which is mention is the first argument.
The map() function returns an iterable which is now converted into a string and then it passes to the join() method.
Using sep keyword in print:
Separator, written as “sep” is a keyword which is used in a print statement when you want to separate two different values or objects in a print statement with a specific string.
![]()
* written in front of apples causes apples to be unpacked in items and converted into a string, then these items are combined with value which is specified in the sep keyword.
If you just want to separate the items and print a list without the brackets and single quotes, then you don’t need to specify the value of sep because it has a default value of whitespace.