Skip to content
This repository was archived by the owner on Jul 7, 2023. It is now read-only.

Commit abd5ea2

Browse files
lgeigerafrozenator
authored andcommitted
Replace .append loop with list comprehension (#1451)
This PR replaces loops that only append to a list with list comprehensions. This makes it more concise and arguably more readably. List comprehensions also are quite a bit faster than appending to a list. Toy example in Python 3.6: ```python In [1]: %%timeit ...: l = [] ...: for i in range(5000): ...: l.append(i) 375 µs ± 1.73 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [2]: %%timeit ...: l = [i for i in range(5000)] 168 µs ± 1.08 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) ```
1 parent a8c246c commit abd5ea2

File tree

11 files changed

+35
-63
lines changed

11 files changed

+35
-63
lines changed

tensor2tensor/data_generators/cnn_dailymail.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,9 +118,7 @@ def generate_hash(inp):
118118

119119
all_files_map = {f.split("/")[-1]: f for f in all_files}
120120

121-
urls = []
122-
for line in tf.gfile.Open(url_file):
123-
urls.append(line.strip().encode("utf-8"))
121+
urls = [line.strip().encode("utf-8") for line in tf.gfile.Open(url_file)]
124122

125123
filelist = []
126124
for url in urls:

tensor2tensor/data_generators/multi_problem_v2.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -370,9 +370,8 @@ def epoch_rates_to_pmf(problems, epoch_rates=None):
370370
"""
371371
if epoch_rates is None:
372372
epoch_rates = [1.0] * len(problems)
373-
example_rates = []
374-
for p, epoch_rate in zip(problems, epoch_rates):
375-
example_rates.append(epoch_rate * p.num_training_examples)
373+
example_rates = [epoch_rate * p.num_training_examples
374+
for p, epoch_rate in zip(problems, epoch_rates)]
376375
return example_rates_to_pmf(example_rates)
377376

378377

tensor2tensor/data_generators/video_utils.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,8 @@
4545

4646

4747
def resize_video_frames(images, size):
48-
resized_images = []
49-
for image in images:
50-
resized_images.append(
51-
tf.to_int64(
52-
tf.image.resize_images(image, [size, size],
53-
tf.image.ResizeMethod.BILINEAR)))
54-
return resized_images
48+
return [tf.to_int64(tf.image.resize_images(
49+
image, [size, size], tf.image.ResizeMethod.BILINEAR)) for image in images]
5550

5651

5752
def video_augmentation(features, hue=False, saturate=False, contrast=False):

tensor2tensor/envs/env_problem.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -256,13 +256,11 @@ def initialize_environments(self, batch_size=1, max_episode_steps=-1,
256256
assert batch_size >= 1
257257
self._batch_size = batch_size
258258

259-
self._envs = []
260-
for _ in range(batch_size):
261-
self._envs.append(
262-
gym_utils.make_gym_env(
263-
self.base_env_name,
264-
rl_env_max_episode_steps=max_episode_steps,
265-
maxskip_env=max_and_skip_env))
259+
self._envs = [
260+
gym_utils.make_gym_env(
261+
self.base_env_name,
262+
rl_env_max_episode_steps=max_episode_steps,
263+
maxskip_env=max_and_skip_env) for _ in range(batch_size)]
266264

267265
# If self.observation_space and self.action_space aren't None, then it means
268266
# that this is a re-initialization of this class, in that case make sure

tensor2tensor/insights/server.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -145,13 +145,11 @@ def list_models(): # pylint: disable=unused-variable
145145
Returns:
146146
JSON for the supported models.
147147
"""
148-
configuration_list = []
149-
for source_code, target_code, label in processors:
150-
configuration_list.append({
151-
"id": label,
152-
"source_language": languages[source_code],
153-
"target_language": languages[target_code],
154-
})
148+
configuration_list = [{
149+
"id": label,
150+
"source_language": languages[source_code],
151+
"target_language": languages[target_code],
152+
} for source_code, target_code, label in processors]
155153
return jsonify({
156154
"configuration": configuration_list
157155
})

tensor2tensor/layers/discretization.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -235,9 +235,8 @@ def bit_to_int(x_bit, num_bits, base=2):
235235
Integer representation of this number.
236236
"""
237237
x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits])))
238-
x_labels = []
239-
for i in range(num_bits):
240-
x_labels.append(x_l[:, i] * tf.to_int32(base)**tf.to_int32(i))
238+
x_labels = [
239+
x_l[:, i] * tf.to_int32(base)**tf.to_int32(i) for i in range(num_bits)]
241240
res = sum(x_labels)
242241
return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1]))
243242

@@ -254,12 +253,9 @@ def int_to_bit(x_int, num_bits, base=2):
254253
Corresponding number expressed in base.
255254
"""
256255
x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
257-
x_labels = []
258-
for i in range(num_bits):
259-
x_labels.append(
260-
tf.floormod(
261-
tf.floordiv(tf.to_int32(x_l),
262-
tf.to_int32(base)**i), tf.to_int32(base)))
256+
x_labels = [tf.floormod(
257+
tf.floordiv(tf.to_int32(x_l), tf.to_int32(base)**i), tf.to_int32(base))
258+
for i in range(num_bits)]
263259
res = tf.concat(x_labels, axis=-1)
264260
return tf.to_float(res)
265261

tensor2tensor/layers/vq_discrete.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,8 @@ def bit_to_int(self, x_bit, num_bits, base=2):
158158
Integer representation of this number.
159159
"""
160160
x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits])))
161-
x_labels = []
162-
for i in range(num_bits):
163-
x_labels.append(x_l[:, i] * tf.to_int32(base)**tf.to_int32(i))
161+
x_labels = [
162+
x_l[:, i] * tf.to_int32(base)**tf.to_int32(i) for i in range(num_bits)]
164163
res = sum(x_labels)
165164
return tf.to_int32(tf.reshape(res, common_layers.shape_list(x_bit)[:-1]))
166165

@@ -177,12 +176,11 @@ def int_to_bit(self, x_int, num_bits, base=2):
177176
Corresponding number expressed in base.
178177
"""
179178
x_l = tf.to_int32(tf.expand_dims(x_int, axis=-1))
180-
x_labels = []
181-
for i in range(num_bits):
182-
x_labels.append(
183-
tf.floormod(
184-
tf.floordiv(tf.to_int32(x_l),
185-
tf.to_int32(base)**i), tf.to_int32(base)))
179+
x_labels = [
180+
tf.floormod(
181+
tf.floordiv(tf.to_int32(x_l),
182+
tf.to_int32(base)**i), tf.to_int32(base))
183+
for i in range(num_bits)]
186184
res = tf.concat(x_labels, axis=-1)
187185
return tf.to_float(res)
188186

tensor2tensor/models/video/base.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -303,10 +303,9 @@ def get_scheduled_sample_inputs(self,
303303
def sample():
304304
"""Calculate the scheduled sampling params based on iteration number."""
305305
with tf.variable_scope("scheduled_sampling", reuse=tf.AUTO_REUSE):
306-
output_items = []
307-
for item_gt, item_gen in zip(groundtruth_items, generated_items):
308-
output_items.append(scheduled_sampling_func(item_gt, item_gen))
309-
return output_items
306+
return [
307+
scheduled_sampling_func(item_gt, item_gen)
308+
for item_gt, item_gen in zip(groundtruth_items, generated_items)]
310309

311310
cases = [
312311
(tf.logical_not(done_warm_start), lambda: groundtruth_items),

tensor2tensor/rl/player.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -177,12 +177,9 @@ def get_keys_to_action(self):
177177
keys_to_action = {}
178178

179179
for action_id, action_meaning in enumerate(self.action_meanings):
180-
keys = []
181-
for keyword, key in keyword_to_key.items():
182-
if keyword in action_meaning:
183-
keys.append(key)
184-
keys_tuple = tuple(sorted(keys))
185-
del keys
180+
keys_tuple = tuple(sorted([
181+
key for keyword, key in keyword_to_key.items()
182+
if keyword in action_meaning]))
186183
assert keys_tuple not in keys_to_action
187184
keys_to_action[keys_tuple] = action_id
188185

tensor2tensor/utils/data_reader.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -300,9 +300,7 @@ def _pad_batch(features, batch_multiple):
300300
padded_features = {}
301301
for k, feature in features.items():
302302
rank = len(feature.shape)
303-
paddings = []
304-
for _ in range(rank):
305-
paddings.append([0, 0])
303+
paddings = [[0, 0] for _ in range(rank)]
306304
paddings[0][1] = batch_padding
307305
padded_feature = tf.pad(feature, paddings)
308306
padded_features[k] = padded_feature

0 commit comments

Comments
 (0)