简体   繁体   中英

how to print return function in Python

It is very strange in Python that, I need specify the return vector and print them out. My original code is:

import scipy.cluster.vq as spk
result = spk.kmeans2(dataset, 5)
print result.label

or like this:

import scipy.cluster.vq as spk
print spk.kmeans2(dataset, 5).label

I got an error: AttributeError: 'tuple' object has no attribute 'label'

However, when I change the code to:

import scipy.cluster.vq as spk
code, label = spk.kmeans2(dataset, 5)
print label

The code works fine. So what is the problem?

The result is a tuple. A tuple can be accessed with index. So the right way to access the data will be

import scipy.cluster.vq as spa
print spk.kmeans2(dataset, 5)[0]  # for code
print spk.kmeans2(dataset, 5)[1]  # for label

That should work. Do read https://docs.python.org/2/tutorial/datastructures.html for more info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM