如何在二维列表的项内追加?

时间:2019-04-11 18:07:07

标签: python python-3.x list

我将python中的字典转换为列表。现在,我想将1附加到该列表的每个元素。当我在循环中打印单个元素时,它表明追加了1,但是当我打印列表时,它没有追加。

代码

apple = {'a':1,'p':2,'l':1,'e':1}

apple_list = apple.items()

for item in apple_list:

    item = list(item)

    item.append(1)

    print(item)

print(apple_list)

输出

['a', 1, 1]
['p', 2, 1]
['l', 1, 1]
['e', 1, 1]

dict_items([('a', 1), ('p', 2), ('l', 1), ('e', 1)])

1 个答案:

答案 0 :(得分:0)

import tensorflow as tf from keras.backend.tensorflow_backend import set_session import numpy as np tf.enable_eager_execution() print(tf.executing_eagerly()) config = tf.ConfigProto() config.gpu_options.allow_growth = True sess = tf.Session(config=config) set_session(sess) class PGEagerAtariNetwork: def __init__(self, state_space, action_space, lr, gamma): self.state_space = state_space self.action_space = action_space self.gamma = gamma self.model = tf.keras.Sequential() # Conv self.model.add( tf.keras.layers.Conv2D(filters=32, kernel_size=[8, 8], strides=[4, 4], activation='relu', input_shape=(84, 84, 4,), name='conv1')) self.model.add( tf.keras.layers.Conv2D(filters=64, kernel_size=[4, 4], strides=[2, 2], activation='relu', name='conv2')) self.model.add( tf.keras.layers.Conv2D(filters=128, kernel_size=[4, 4], strides=[2, 2], activation='relu', name='conv3')) self.model.add(tf.keras.layers.Flatten(name='flatten')) # Fully connected self.model.add(tf.keras.layers.Dense(units=512, activation='relu', name='fc1')) self.model.add(tf.keras.layers.Dropout(rate=0.4, name='dr1')) self.model.add(tf.keras.layers.Dense(units=256, activation='relu', name='fc2')) self.model.add(tf.keras.layers.Dropout(rate=0.3, name='dr2')) self.model.add(tf.keras.layers.Dense(units=128, activation='relu', name='fc3')) self.model.add(tf.keras.layers.Dropout(rate=0.1, name='dr3')) # Logits self.model.add(tf.keras.layers.Dense(units=self.action_space, activation=None, name='logits')) self.model.summary() # Optimizer self.optimizer = tf.train.AdamOptimizer(learning_rate=lr) def get_probs(self, s): s = s[np.newaxis, :] logits = self.model.predict(s) probs = tf.nn.softmax(logits).numpy() return probs def update_policy(self, s, r, a): with tf.GradientTape() as tape: logits = self.model.predict(s) policy_loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=a, logits=logits) policy_loss = policy_loss * tf.stop_gradient(r) loss = tf.reduce_mean(policy_loss) grads = tape.gradient(loss, self.model.trainable_variables) self.optimizer.apply_gradients(zip(grads, self.model.trainable_variables)) item生成的序列中的元组。通过将apple.items()分配给list(item),就为变量分配了一个新列表,这样它就不再引用序列中的元组。

您可以改为将dict项目转换为具有列表理解的列表列表,同时将键值对的元组与item的单例连接起来:

1

这将返回:

[list(pair + (1,)) for pair in apple.items()]