无法实现检查函数:执行时返回TypeError: tuple indices must be integers or slices, not str错误求助
Let's break down exactly what's going on here. That error message is telling you a clear problem: you're trying to use a string (like 'qnts') to index a tuple, but tuples only accept integers or slices as indices—they don't support key-based access like dictionaries do.
Looking at your code, the root issue is how you're handling the return value of load_data:
data1 = load_data('gm_2020.npz') qtty1 = data1['qnts'] # This line fails because data1 is a tuple, not a dictionary
Why this happens
You assumed load_data returns a dictionary (where you can use key names to pull values), but it's actually returning a tuple. Tuples are ordered, position-based collections, so string keys won't work here.
How to fix it
First, let's confirm the type of data you're getting. Add these quick debug lines to your code to verify:
data1 = load_data('gm_2020.npz') print(type(data1)) # This will print <class 'tuple'> if our hunch is correct print(data1) # This shows you the order of elements in the tuple
Once you know the tuple's element order, you have two clean solutions:
Unpack the tuple directly (most readable approach):
Ifload_datareturns values in the order(qnts, models), rewrite your variable assignments to unpack the tuple immediately:def sel_models(): # Unpack the tuple returned by load_data to get your variables directly qtty1, dcng1 = load_data('gm_2020.npz') qtty2, dcng2 = load_data('gm_2021.npz') mask20 = (dcng1 == 'Damas') | (dcng1 == 'Cobalt') | (dcng1 == 'Nexia') | (dcng1 == 'Gentra') mask21 = (dcng2 == 'Damas') | (dcng2 == 'Cobalt') | (dcng2 == 'Nexia') | (dcng2 == 'Gentra') return qtty1[mask20], qtty2[mask21]Use integer indices (if unpacking isn't feasible):
If the tuple order placesqntsat index 0 andmodelsat index 1, access them with integer positions:def sel_models(): data1 = load_data('gm_2020.npz') data2 = load_data('gm_2021.npz') qtty1 = data1[0] qtty2 = data2[0] dcng1 = data1[1] dcng2 = data2[1] mask20 = (dcng1 == 'Damas') | (dcng1 == 'Cobalt') | (dcng1 == 'Nexia') | (dcng1 == 'Gentra') mask21 = (dcng2 == 'Damas') | (dcng2 == 'Cobalt') | (dcng2 == 'Nexia') | (dcng2 == 'Gentra') return qtty1[mask20], qtty2[mask21]
Quick side note
If load_data is a wrapper around numpy.load for .npz files, normally np.load returns an NpzFile object that acts like a dictionary. If that's the case, your load_data function might be modifying the return value (e.g., converting it to a tuple with .values()). Double-check the load_data implementation if you're still stuck!
内容的提问来源于stack exchange,提问作者okiljon olimjonov

