【问题标题】:Print.format() function not working in PythonPrint.format() 函数在 Python 中不起作用
【发布时间】:2019-01-22 11:53:52
【问题描述】:

我正在使用来自 scikit-learn 的数据集,我目前正在使用 iris 数据集(用于分类不同种类虹膜的数据集)。 当我尝试使用打印添加此代码来可视化描述花朵特征的值时:

from sklearn.datasets import load_iris iris_dataset=load_iris() print("Keys of the iris dataset:\n".format(iris_dataset['feature_names']))

我只是从控制台获得这个输出:

鸢尾花数据集的键:

另一方面,如果我在这一行中使用不带“格式”的打印功能:

print("Keys of the iris dataset:\n",(iris_dataset['feature_names']))

我至少获得了一个输出:

('鸢尾花数据集的keys:\n', ['萼片长度(cm)', '萼片宽度(cm)', '花瓣长度(cm)', '花瓣宽度(cm)' ])

我尝试显示的数据集的每个部分都会发生这种情况,这似乎是函数 format() 的问题,有没有人有任何解决它的建议并正确可视化格式化的输出?

【问题讨论】:

    标签: python printing scikit-learn


    【解决方案1】:

    您缺少花括号{},它们本质上是占位符。它们将被str.format 函数中指定的变量替换。请试试这个:

    print("Keys of the iris dataset:\n{}".format(iris_dataset['feature_names']))
    

    这会给你:

    Keys of the iris dataset:
    ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
    

    请查看documentation 或网络上Python string format() 上的众多教程之一。

    【讨论】:

      【解决方案2】:

      您的格式字符串没有任何要插入的内容。 对于要放入字符串的每个参数,您需要在某处使用{},如下所示:

      >>> print("Keys of the iris dataset: {}\n".format(iris_dataset['feature_names'])
      )
      Keys of the iris dataset: ['sepal length (cm)', 'sepal width (cm)', 'petal lengt
      h (cm)', 'petal width (cm)']
      

      【讨论】:

        猜你喜欢
        • 2019-11-19
        • 1970-01-01
        • 2021-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-04
        相关资源
        最近更新 更多