import numpy as np
custom = {
1: {'a': np.zeros(10), 'b': np.zeros(100)},
2:{'c': np.zeros(20), 'd': np.zeros(200)}
}
my_gen = (
(key, subkey, np_array)
for (key, a_dict) in custom.items()
for subkey, np_array in a_dict.items()
)
for key, subkey, np_array in my_gen:
print(key, subkey, np_array)
--output:--
1 b [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
1 a [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
2 d [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0.]
2 c [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0.]
Или вы могли бы восстановить структуру данных в нечто, что является более полезным для ваших целей:
import numpy as np
custom = {
1: {'a': np.zeros(10), 'b': np.zeros(100)},
2:{'c': np.zeros(20), 'd': np.zeros(200)}
}
#Create a *list* of tuples:
converted_data = [
(np_array, subkey, key)
for (key, a_dict) in custom.items()
for subkey, np_array in a_dict.items()
]
for np_array, subkey, key in converted_data:
print(key, subkey, np_array)
Создание пользовательского итератора:
class Dog:
def __init__(self, data):
self.data = data
self.max = len(data)
self.index_pointer = 0
def __next__(self):
index = self.index_pointer
if index < self.max:
current_val = self.data[index]
self.index_pointer += 1
return current_val
else:
raise StopIteration
class MyIter:
def __iter__(self):
return Dog([1, 2, 3])
for i in MyIter():
print(i)
--output:--
1
2
3
__iter__()
просто необходимо для возврата объекта, который реализует метод __next__()
, поэтому вы можете комбинировать новления два класса, как это:
class MyIter:
def __init__(self, data):
self.data = data
self.max = len(data)
self.index_pointer = 0
def __iter__(self):
return self #I have a __next__() method, so let's return me!
def __next__(self):
index = self.index_pointer
if index < self.max:
current_val = self.data[index]
self.index_pointer += 1
return current_val
else:
raise StopIteration
for i in MyIter([1, 2, 3]):
print(i)
--output:--
1
2
3
Более сложный __next__()
метод:
import numpy as np
class CustomIter:
def __init__(self, data):
self.data = data
self.count = 0
def __iter__(self):
return self
def __next__(self):
count = self.count
self.count += 1
if count == 0: #On first iteration, retun a sum of the keys
return sum(self.data.keys())
elif count == 1: #On second iteration, return the subkeys in tuples
subkeys = [
a_dict.keys()
for a_dict in self.data.values()
]
return subkeys
elif count == 2: #On third iteration, return the count of np arrays
np_arrays = [
np_array
for a_dict in self.data.values()
for np_array in a_dict.values()
]
return len(np_arrays)
else: #Quit after three iterations
raise StopIteration
custom = {
1: {'a': np.zeros(10), 'b': np.zeros(100)},
2:{'c': np.zeros(20), 'd': np.zeros(200)}
}
for i in CustomIter(custom):
print(i)
--output:--
3
[dict_keys(['b', 'a']), dict_keys(['d', 'c'])]
4
Спасибо, что ответили. В чем разница между наличием 'my_gen' в вашем решении и' custom_dict_iter' в решении @ tdelaney? – aaragon
@aarogon, вы можете напрямую определять генераторы - без определения функции. Тем не менее, вы не можете перемотать генератор, поэтому, если вы хотите получить еще один генератор позже, я бы пошел с решением tdelaney – 7stud
Doest, что означает, что ваше решение работает только один раз? – aaragon