标签归档:output-formatting

TypeError:并非在字符串格式化python期间转换所有参数

问题:TypeError:并非在字符串格式化python期间转换所有参数

该程序应采用两个名称,如果它们的长度相同,则应检查它们是否相同。如果是相同的单词,则将显示“名称相同”。如果它们的长度相同但字母不同,则会显示“名称不同但长度相同”。我有问题的部分在底部的4行中。

#!/usr/bin/env python
# Enter your code for "What's In (The Length Of) A Name?" here.
name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
    if len(name1) > len(name2):
        print ("'{0}' is longer than '{1}'"% name1, name2)
    elif len(name1) < len(name2):
        print ("'{0}'is longer than '{1}'"% name2, name1)

当我运行此代码时,它显示:

Traceback (most recent call last):
  File "program.py", line 13, in <module>
    print ("'{0}' is longer than '{1}'"% name1, name2)
TypeError: not all arguments converted during string formatting

任何建议,高度赞赏。

The program is supposed to take in two names, and if they are the same length it should check if they are the same word. If it’s the same word it will print “The names are the same”. If they are the same length but with different letters it will print “The names are different but the same length”. The part I’m having a problem with is in the bottom 4 lines.

#!/usr/bin/env python
# Enter your code for "What's In (The Length Of) A Name?" here.
name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
    if len(name1) > len(name2):
        print ("'{0}' is longer than '{1}'"% name1, name2)
    elif len(name1) < len(name2):
        print ("'{0}'is longer than '{1}'"% name2, name1)

When I run this code it displays:

Traceback (most recent call last):
  File "program.py", line 13, in <module>
    print ("'{0}' is longer than '{1}'"% name1, name2)
TypeError: not all arguments converted during string formatting

Any suggestions are highly appreciated.


回答 0

您正在混合使用不同的格式功能。

旧式%格式化使用%代码进行格式化:

'It will cost $%d dollars.' % 95

新型{}格式使用{}代码和.format方法

'It will cost ${0} dollars.'.format(95)

请注意,使用旧格式时,必须使用元组指定多个参数:

'%d days and %d nights' % (40, 40)

就您而言,由于您使用的是{}格式说明符,请使用.format

"'{0}' is longer than '{1}'".format(name1, name2)

You’re mixing different format functions.

The old-style % formatting uses % codes for formatting:

'It will cost $%d dollars.' % 95

The new-style {} formatting uses {} codes and the .format method

'It will cost ${0} dollars.'.format(95)

Note that with old-style formatting, you have to specify multiple arguments using a tuple:

'%d days and %d nights' % (40, 40)

In your case, since you’re using {} format specifiers, use .format:

"'{0}' is longer than '{1}'".format(name1, name2)

回答 1

错误在于您的字符串格式。

使用’%’运算符使用传统字符串格式的正确方法是使用printf样式的格式字符串(此处的Python文档:http : //docs.python.org/2/library/string.html#format-字符串语法):

"'%s' is longer than '%s'" % (name1, name2)

但是,’%’运算符将来可能会被弃用。新的PEP 3101做事方式是这样的:

"'{0}' is longer than '{1}'".format(name1, name2)

The error is in your string formatting.

The correct way to use traditional string formatting using the ‘%’ operator is to use a printf-style format string (Python documentation for this here: http://docs.python.org/2/library/string.html#format-string-syntax):

"'%s' is longer than '%s'" % (name1, name2)

However, the ‘%’ operator will probably be deprecated in the future. The new PEP 3101 way of doing things is like this:

"'{0}' is longer than '{1}'".format(name1, name2)

回答 2

对我来说,此错误是在我试图将元组传递给字符串格式方法时引起的。

我从这个问题/答案中找到了解决方案

从链接中复制并粘贴正确答案(“不做我的工作”)

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

用感兴趣的元组作为唯一项(即(tutuple)部分)制作单例元组是这里的关键。

For me, This error was caused when I was attempting to pass in a tuple into the string format method.

I found the solution from this question/answer

Copying and pasting the correct answer from the link (NOT MY WORK):

>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.


回答 3

就我而言,这是因为我只需要一个%s,我就缺少值输入。

In my case, it’s because I need only a single %s, i missing values input.


回答 4

除了其他两个答案,我认为缩进在最后两个条件下也是不正确的。条件是一个名字要长于另一个名字,并且它们必须以“ elif”开头且没有缩进。如果将其放在第一个条件下(通过从边缘开始给它四个缩进),则最终会导致矛盾,因为名称的长度不能同时相等且不同。

    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))

In addition to the other two answers, I think the indentations are also incorrect in the last two conditions. The conditions are that one name is longer than the other and they need to start with ‘elif’ and with no indentations. If you put it within the first condition (by giving it four indentations from the margin), it ends up being contradictory because the lengths of the names cannot be equal and different at the same time.

    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))

回答 5

其他一些答案中也指出了很多问题。

  1. 正如nneonneo所指出的,您正在混合使用不同的字符串格式化方法。
  2. 正如GuyP指出的那样,您的缩进也已关闭。

我既提供了.format的示例,也提供了将元组传递给%s的参数说明符的方法。在这两种情况下,缩进均已固定,因此长度匹配时大于/小于检查范围。也将随后的if语句更改为elif,以便仅在先前的同一级别语句为False时才运行。

使用.format进行字符串格式化

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
    print ("{0} is longer than {1}".format(name2, name1))

使用%s和元组进行字符串格式化

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("%s is longer than %s" % (name1, name2))
elif len(name1) < len(name2):
    print ("%s is longer than %s" % (name2, name1))

There is a combination of issues as pointed out in a few of the other answers.

  1. As pointed out by nneonneo you are mixing different String Formatting methods.
  2. As pointed out by GuyP your indentation is off as well.

I’ve provided both the example of .format as well as passing tuples to the argument specifier of %s. In both cases the indentation has been fixed so greater/less than checks are outside of when length matches. Also changed subsequent if statements to elif’s so they only run if the prior same level statement was False.

String Formatting with .format

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
    print ("{0} is longer than {1}".format(name2, name1))

String Formatting with %s and a tuple

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
    if name1 == name2:
        print ("The names are the same")
    else:
        print ("The names are different, but are the same length")
elif len(name1) > len(name2):
    print ("%s is longer than %s" % (name1, name2))
elif len(name1) < len(name2):
    print ("%s is longer than %s" % (name2, name1))

回答 6

在python 3.7及更高版本中,有一种新的简便方法。语法如下:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

输出:

Hello, Eric. You are 74.

In python 3.7 and above there is a new and easy way. here is the syntax:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

OutPut:

Hello, Eric. You are 74.

回答 7

我也遇到错误

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting 

但是列表参数工作良好。

我使用mysqlclient python lib。lib似乎不接受元组args。像这样传递列表参数['arg1', 'arg2'] 将起作用。

I encounter the error as well,

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting 

But list args work well.

I use mysqlclient python lib. The lib looks like not to accept tuple args. To pass list args like ['arg1', 'arg2'] will work.


回答 8

Django原始SQL查询视图

"SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to)

models.py

class VehicleDamage(models.Model):
    requestdate = models.DateTimeField("requestdate")
    vendor_name = models.CharField("vendor_name", max_length=50)
    class Meta:
        managed=False

views.py

def location_damageReports(request):
    #static date for testing
    date_from = '2019-11-01'
    date_to = '2019-21-01'
    vehicle_damage_reports = VehicleDamage.objects.raw("SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to))
    damage_report = DashboardDamageReportSerializer(vehicle_damage_reports, many=True)
    data={"data": damage_report.data}
    return HttpResponse(json.dumps(data), content_type="application/json")

注意:使用python 3.5和Django 1.11

django raw sql query in view

"SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to)

models.py

class VehicleDamage(models.Model):
    requestdate = models.DateTimeField("requestdate")
    vendor_name = models.CharField("vendor_name", max_length=50)
    class Meta:
        managed=False

views.py

def location_damageReports(request):
    #static date for testing
    date_from = '2019-11-01'
    date_to = '2019-21-01'
    vehicle_damage_reports = VehicleDamage.objects.raw("SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to))
    damage_report = DashboardDamageReportSerializer(vehicle_damage_reports, many=True)
    data={"data": damage_report.data}
    return HttpResponse(json.dumps(data), content_type="application/json")

Note: using python 3.5 and django 1.11


回答 9

对我来说,因为我在一个打印调用中存储了许多值,所以解决方案是创建一个单独的变量以将数据存储为元组,然后调用打印函数。

x = (f"{id}", f"{name}", f"{age}")
print(x) 

For me, as I was storing many values within a single print call, the solution was to create a separate variable to store the data as a tuple and then call the print function.

x = (f"{id}", f"{name}", f"{age}")
print(x) 

如何在不截断的情况下打印完整的NumPy数组?

问题:如何在不截断的情况下打印完整的NumPy数组?

当我打印一个numpy数组时,我得到一个截断的表示形式,但是我想要完整的数组。

有什么办法吗?

例子:

>>> numpy.arange(10000)
array([   0,    1,    2, ..., 9997, 9998, 9999])

>>> numpy.arange(10000).reshape(250,40)
array([[   0,    1,    2, ...,   37,   38,   39],
       [  40,   41,   42, ...,   77,   78,   79],
       [  80,   81,   82, ...,  117,  118,  119],
       ..., 
       [9880, 9881, 9882, ..., 9917, 9918, 9919],
       [9920, 9921, 9922, ..., 9957, 9958, 9959],
       [9960, 9961, 9962, ..., 9997, 9998, 9999]])

When I print a numpy array, I get a truncated representation, but I want the full array.

Is there any way to do this?

Examples:

>>> numpy.arange(10000)
array([   0,    1,    2, ..., 9997, 9998, 9999])

>>> numpy.arange(10000).reshape(250,40)
array([[   0,    1,    2, ...,   37,   38,   39],
       [  40,   41,   42, ...,   77,   78,   79],
       [  80,   81,   82, ...,  117,  118,  119],
       ..., 
       [9880, 9881, 9882, ..., 9917, 9918, 9919],
       [9920, 9921, 9922, ..., 9957, 9958, 9959],
       [9960, 9961, 9962, ..., 9997, 9998, 9999]])

回答 0

用途numpy.set_printoptions

import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)

Use numpy.set_printoptions:

import sys
import numpy
numpy.set_printoptions(threshold=sys.maxsize)

回答 1

import numpy as np
np.set_printoptions(threshold=np.inf)

我建议使用,np.inf而不是np.nan别人建议的。它们都为您的目的而工作,但是通过将阈值设置为“无穷大”,对于每个阅读您的代码的人来说都是显而易见的。对我来说,达到“没有数字”的门槛似乎有点模糊。

import numpy as np
np.set_printoptions(threshold=np.inf)

I suggest using np.inf instead of np.nan which is suggested by others. They both work for your purpose, but by setting the threshold to “infinity” it is obvious to everybody reading your code what you mean. Having a threshold of “not a number” seems a little vague to me.


回答 2

先前的答案是正确的,但是作为较弱的选择,您可以转换为列表:

>>> numpy.arange(100).reshape(25,4).tolist()

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21,
22, 23], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35], [36, 37, 38, 39], [40, 41,
42, 43], [44, 45, 46, 47], [48, 49, 50, 51], [52, 53, 54, 55], [56, 57, 58, 59], [60, 61,
62, 63], [64, 65, 66, 67], [68, 69, 70, 71], [72, 73, 74, 75], [76, 77, 78, 79], [80, 81,
82, 83], [84, 85, 86, 87], [88, 89, 90, 91], [92, 93, 94, 95], [96, 97, 98, 99]]

The previous answers are the correct ones, but as a weaker alternative you can transform into a list:

>>> numpy.arange(100).reshape(25,4).tolist()

[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21,
22, 23], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35], [36, 37, 38, 39], [40, 41,
42, 43], [44, 45, 46, 47], [48, 49, 50, 51], [52, 53, 54, 55], [56, 57, 58, 59], [60, 61,
62, 63], [64, 65, 66, 67], [68, 69, 70, 71], [72, 73, 74, 75], [76, 77, 78, 79], [80, 81,
82, 83], [84, 85, 86, 87], [88, 89, 90, 91], [92, 93, 94, 95], [96, 97, 98, 99]]

回答 3

NumPy 1.15或更高版本

如果您使用NumPy 1.15(2018年7月23日发行)或更高版本,则可以使用printoptions上下文管理器:

with numpy.printoptions(threshold=numpy.inf):
    print(arr)

(当然,如果您导入的方式是,请替换numpy为)npnumpy

使用上下文管理器(with-block)可确保在上下文管理器完成后,打印选项将恢复为块启动之前的状态。它确保设置是临时的,并且仅应用于块内的代码。

有关上下文管理器及其支持的其他参数的详细信息,请参见numpy.printoptions文档

NumPy 1.15 or newer

If you use NumPy 1.15 (released 2018-07-23) or newer, you can use the printoptions context manager:

with numpy.printoptions(threshold=numpy.inf):
    print(arr)

(of course, replace numpy by np if that’s how you imported numpy)

The use of a context manager (the with-block) ensures that after the context manager is finished, the print options will revert to whatever they were before the block started. It ensures the setting is temporary, and only applied to code within the block.

See numpy.printoptions documentation for details on the context manager and what other arguments it supports.


回答 4

听起来您正在使用numpy。

如果是这样,您可以添加:

import numpy as np
np.set_printoptions(threshold=np.nan)

这将禁用边角打印。有关更多信息,请参见此NumPy教程

This sounds like you’re using numpy.

If that’s the case, you can add:

import numpy as np
np.set_printoptions(threshold=np.nan)

That will disable the corner printing. For more information, see this NumPy Tutorial.


回答 5

这是一种一次性的方法,如果您不想更改默认设置,这将非常有用:

def fullprint(*args, **kwargs):
  from pprint import pprint
  import numpy
  opt = numpy.get_printoptions()
  numpy.set_printoptions(threshold=numpy.inf)
  pprint(*args, **kwargs)
  numpy.set_printoptions(**opt)

Here is a one-off way to do this, which is useful if you don’t want to change your default settings:

def fullprint(*args, **kwargs):
  from pprint import pprint
  import numpy
  opt = numpy.get_printoptions()
  numpy.set_printoptions(threshold=numpy.inf)
  pprint(*args, **kwargs)
  numpy.set_printoptions(**opt)

回答 6

使用上下文管理作为保价 sugggested

import numpy as np


class fullprint:
    'context manager for printing full numpy arrays'

    def __init__(self, **kwargs):
        kwargs.setdefault('threshold', np.inf)
        self.opt = kwargs

    def __enter__(self):
        self._opt = np.get_printoptions()
        np.set_printoptions(**self.opt)

    def __exit__(self, type, value, traceback):
        np.set_printoptions(**self._opt)


if __name__ == '__main__': 
    a = np.arange(1001)

    with fullprint():
        print(a)

    print(a)

    with fullprint(threshold=None, edgeitems=10):
        print(a)

Using a context manager as Paul Price sugggested

import numpy as np


class fullprint:
    'context manager for printing full numpy arrays'

    def __init__(self, **kwargs):
        kwargs.setdefault('threshold', np.inf)
        self.opt = kwargs

    def __enter__(self):
        self._opt = np.get_printoptions()
        np.set_printoptions(**self.opt)

    def __exit__(self, type, value, traceback):
        np.set_printoptions(**self._opt)


if __name__ == '__main__': 
    a = np.arange(1001)

    with fullprint():
        print(a)

    print(a)

    with fullprint(threshold=None, edgeitems=10):
        print(a)

回答 7

numpy.savetxt

numpy.savetxt(sys.stdout, numpy.arange(10000))

或者如果您需要一个字符串:

import StringIO
sio = StringIO.StringIO()
numpy.savetxt(sio, numpy.arange(10000))
s = sio.getvalue()
print s

默认输出格式为:

0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
...

并可以使用其他参数进行配置。

特别要注意的是,它也不会显示方括号,并允许进行大量自定义,如以下内容所述:如何打印不带括号的Numpy数组?

在python 2.7.12,numpy 1.11.1上测试。

numpy.savetxt

numpy.savetxt(sys.stdout, numpy.arange(10000))

or if you need a string:

import StringIO
sio = StringIO.StringIO()
numpy.savetxt(sio, numpy.arange(10000))
s = sio.getvalue()
print s

The default output format is:

0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
...

and it can be configured with further arguments.

Note in particular how this also not shows the square brackets, and allows for a lot of customization, as mentioned at: How to print a Numpy array without brackets?

Tested on Python 2.7.12, numpy 1.11.1.


回答 8

这是一个微小的修饰(除去传递额外的参数选项set_printoptions)neok的回答。

它显示了如何使用contextlib.contextmanager更少的代码行轻松地创建这样的contextmanager:

import numpy as np
from contextlib import contextmanager

@contextmanager
def show_complete_array():
    oldoptions = np.get_printoptions()
    np.set_printoptions(threshold=np.inf)
    try:
        yield
    finally:
        np.set_printoptions(**oldoptions)

在您的代码中,可以这样使用它:

a = np.arange(1001)

print(a)      # shows the truncated array

with show_complete_array():
    print(a)  # shows the complete array

print(a)      # shows the truncated array (again)

This is a slight modification (removed the option to pass additional arguments to set_printoptions)of neoks answer.

It shows how you can use contextlib.contextmanager to easily create such a contextmanager with fewer lines of code:

import numpy as np
from contextlib import contextmanager

@contextmanager
def show_complete_array():
    oldoptions = np.get_printoptions()
    np.set_printoptions(threshold=np.inf)
    try:
        yield
    finally:
        np.set_printoptions(**oldoptions)

In your code it can be used like this:

a = np.arange(1001)

print(a)      # shows the truncated array

with show_complete_array():
    print(a)  # shows the complete array

print(a)      # shows the truncated array (again)

回答 9

除了最大列数(以固定)之外,此答案numpy.set_printoptions(threshold=numpy.nan)还可以显示一定数量的字符。在某些环境中,例如从bash调用python(而不是交互式会话)时,可以通过如下设置参数来解决此问题linewidth

import numpy as np
np.set_printoptions(linewidth=2000)    # default = 75
Mat = np.arange(20000,20150).reshape(2,75)    # 150 elements (75 columns)
print(Mat)

在这种情况下,您的窗口应限制换行符的字符数。

对于那些使用sublime文本并希望在输出窗口中查看结果的用户,应将build选项添加"word_wrap": false到sublime-build文件[ source ]中。

Complementary to this answer from the maximum number of columns (fixed with numpy.set_printoptions(threshold=numpy.nan)), there is also a limit of characters to be displayed. In some environments like when calling python from bash (rather than the interactive session), this can be fixed by setting the parameter linewidth as following.

import numpy as np
np.set_printoptions(linewidth=2000)    # default = 75
Mat = np.arange(20000,20150).reshape(2,75)    # 150 elements (75 columns)
print(Mat)

In this case, your window should limit the number of characters to wrap the line.

For those out there using sublime text and wanting to see results within the output window, you should add the build option "word_wrap": false to the sublime-build file [source] .


回答 10

从NumPy 1.16版本开始,有关更多详细信息,请参见GitHub票证12251

from sys import maxsize
from numpy import set_printoptions

set_printoptions(threshold=maxsize)

Since NumPy version 1.16, for more details see GitHub ticket 12251.

from sys import maxsize
from numpy import set_printoptions

set_printoptions(threshold=maxsize)

回答 11

要关闭它并返回正常模式

np.set_printoptions(threshold=False)

To turn it off and return to the normal mode

np.set_printoptions(threshold=False)

回答 12

假设您有一个numpy数组

 arr = numpy.arange(10000).reshape(250,40)

如果要一次性打印整个数组(不切换np.set_printoptions),但是想要比上下文管理器更简单(更少的代码)的方法,那就做

for row in arr:
     print row 

Suppose you have a numpy array

 arr = numpy.arange(10000).reshape(250,40)

If you want to print the full array in a one-off way (without toggling np.set_printoptions), but want something simpler (less code) than the context manager, just do

for row in arr:
     print row 

回答 13

稍作修改:(因为您要打印大量列表)

import numpy as np
np.set_printoptions(threshold=np.inf, linewidth=200)

x = np.arange(1000)
print(x)

这将增加每行的字符数(默认线宽为75)。使用任何您喜欢的值作为适合您的编码环境的线宽。通过每行添加更多字符,这将使您不必遍历大量输出行。

A slight modification: (since you are going to print a huge list)

import numpy as np
np.set_printoptions(threshold=np.inf, linewidth=200)

x = np.arange(1000)
print(x)

This will increase the number of characters per line (default linewidth of 75). Use any value you like for the linewidth which suits your coding environment. This will save you from having to go through huge number of output lines by adding more characters per line.


回答 14

您可以使用array2string功能-docs

a = numpy.arange(10000).reshape(250,40)
print(numpy.array2string(a, threshold=numpy.nan, max_line_width=numpy.nan))
# [Big output]

You can use the array2string function – docs.

a = numpy.arange(10000).reshape(250,40)
print(numpy.array2string(a, threshold=numpy.nan, max_line_width=numpy.nan))
# [Big output]

回答 15

您不会总是希望打印所有项目,尤其是对于大型阵列。

一种显示更多项目的简单方法:

In [349]: ar
Out[349]: array([1, 1, 1, ..., 0, 0, 0])

In [350]: ar[:100]
Out[350]:
array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1,
       1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1])

默认情况下,当切片的数组<1000时,它可以正常工作。

You won’t always want all items printed, especially for large arrays.

A simple way to show more items:

In [349]: ar
Out[349]: array([1, 1, 1, ..., 0, 0, 0])

In [350]: ar[:100]
Out[350]:
array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1,
       1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1])

It works fine when sliced array < 1000 by default.


回答 16

如果有熊猫

    numpy.arange(10000).reshape(250,40)
    print(pandas.DataFrame(a).to_string(header=False, index=False))

避免了需要重新设置的副作用,numpy.set_printoptions(threshold=sys.maxsize)并且您没有得到numpy.array和方括号。我发现这很方便将大量数组转储到日志文件中

If you have pandas available,

    numpy.arange(10000).reshape(250,40)
    print(pandas.DataFrame(a).to_string(header=False, index=False))

avoids the side effect of requiring a reset of numpy.set_printoptions(threshold=sys.maxsize) and you don’t get the numpy.array and brackets. I find this convenient for dumping a wide array into a log file


回答 17

如果一个数组太大而无法打印,NumPy会自动跳过该数组的中央部分而仅打印角点:要禁用此行为并强制NumPy打印整个数组,可以使用更改打印选项set_printoptions

>>> np.set_printoptions(threshold='nan')

要么

>>> np.set_printoptions(edgeitems=3,infstr='inf',
... linewidth=75, nanstr='nan', precision=8,
... suppress=False, threshold=1000, formatter=None)

您也可以参考numpy文档 numpy文档中的“或部分”以获取更多帮助。

If an array is too large to be printed, NumPy automatically skips the central part of the array and only prints the corners: To disable this behaviour and force NumPy to print the entire array, you can change the printing options using set_printoptions.

>>> np.set_printoptions(threshold='nan')

or

>>> np.set_printoptions(edgeitems=3,infstr='inf',
... linewidth=75, nanstr='nan', precision=8,
... suppress=False, threshold=1000, formatter=None)

You can also refer to the numpy documentation numpy documentation for “or part” for more help.