我有一个带有嵌套列表的列表。每个嵌套中的第一个元素彼此属于。 嵌套列表是可扩展的。 如果我要调用其关联元素,则尝试返回一个元素。
我可以使用索引列出它们,但是由于嵌套是可扩展的,因此无法正常工作
我在here上放了一个沙盒。
nested = [['nest1_A', 'nest1_B', 'nest1_C'], ['nest2_A', 'nest2_B', 'nest2_C'], ['nest3_A', 'nest3_B', 'nest3_C']]
print(nested,'\n')
print('First Set')
print(nested[0][0])
print(nested[1][0])
print(nested[2][0],'\n')
print('Second Set')
print(nested[0][1])
print(nested[1][1])
print(nested[2][1],'\n')
print('Third Set')
print(nested[0][2])
print(nested[1][2])
print(nested[2][2],'\n')
print('And so on...')
我希望如果我打电话
nest1_A[0]
将返回nest2_A
,
nest1_A[1]
将返回nest3_A
答案 0 :(得分:2)
您可以创建一个循环主列表并在您提供给它的索引处获取子列表项的函数。
def get_nested_elements_by_index(nested_list, index):
return [sub_list[index] for sub_list in nested_list if len(sub_list) > index]
您可以像这样使用列表理解来改善功能:
0
哪怕您甚至忘记该功能,也可以按原样使用它。
例如,对于索引...
first="\n".join(sub_list[0] for sub_list in nested_list),
...
,您可以编写
{{1}}
(最后一个示例是join函数中的迭代器,但其工作原理与列表理解大致相同)
答案 1 :(得分:2)
这就是你想要的吗?
def decode_sequence(input_seq, maxlen_decoder_sequence):
# Encode the input as state vectors.
initial_state = model_encoder.predict(input_seq)
# I simply repeat the encoder states since
# both decoding layers were trained on the encoded-vector
# as initialization. I pass them into model_decoder.predict()
initial_state = initial_state + initial_state
# Generate empty target sequence of length 1.
decoder_input_data = np.zeros((1, 1, num_allowed_chars))
# Populate the first character of target sequence with the start character.
decoder_input_data[0, 0, char_to_int['a']] = 1.
# Sampling loop for a batch of sequences
# (to simplify, here we assume a batch of size 1).
stop_condition = False
decoded_sentence = ''
while not stop_condition:
# catch all returning states to feed them back in (see end of loop)
one_hot_char, h1, c1, h2, c2 = model_decoder.predict(
[decoder_input_data] + initial_state)
one_hot_char = one_hot_char[0][-1]
char_as_int = np.argmax(one_hot_char)
# print(char_as_int)
char_as_char = int_to_char[char_as_int]
decoded_sentence += char_as_char
# Exit condition: either hit max length or find stop character.
# (z is stop-char in this case)
if (char_as_char == 'z' or
len(decoded_sentence) >= maxlen_decoder_sequence):
stop_condition = True
# feed the predicted char back into next prediction step
decoder_input_data = np.zeros((1, 1, num_allowed_chars))
decoder_input_data[0, 0, char_as_int] = 1.
# Update states
initial_state = [h1, c1, h2, c2]
return decoded_sentence
它给出那些结果:
def get_nest(nests, id):
return [x[id] for x in nests if len(x) > id]
如果嵌套列表的大小不同(如果没有,则可以在方法中删除get_nest(nested, 1)
>>> ['nest1_B', 'nest2_B', 'nest3_B']
部分)
if
编辑:删除了方法定义中的提示