简体   繁体   中英

Printing using globals() in Python

I'm trying to print the shape for each dataset but it doesn't print as I would like.

for i in train_set, train_labels, test_set, test_labels:
    name = [x for x in globals() if globals()[x] is i][1]
    print("The {0} shape is {1}".format(name, i.shape))

The output is:

The i shape is (1700, 20)

The i shape is (1700,)

The i shape is (300, 20)

The i shape is (300,)

The value of 'i' is not being replaced. Can someone guide me what's wrong in this:

If this is just for debugging or status info, here's the right way:

for name,table in (
    ('train_set', train_set),
    ('train_labels', train_labels),
    ('test_set', test_set),
    ('test_labels', test_labels) ):
    print("The {0} shape is {1}".format(name, table.shape)

If you need to have the names for more than just this, then don't create them in individual variables:

data['train_set'] = train_set
data['train_labels'] = train_labels
data['test_set'] = test_set
data['test_labels'] = test_labels

Now you have the names and the tables in one convenient location.

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