3 ms·
An example loop: elif cmd.op == 'TUPLE': arity, = cmd.args tuple_args = [] for _ in range(arity): tuple_args.append(sel
by Joker_vD 5y ago
An example loop:
elif cmd.op == 'TUPLE':
arity, = cmd.args
tuple_args = []
for _ in range(arity):
tuple_args.append(self.data_stack.pop())
result = '{' + ', '.join(map(str, tuple_args)) + '}'
self.data_stack.append(result)
Is following use of comprehension any better? I don't think so:
elif cmd.op == 'TUPLE':
arity, = cmd.args
tuple_args = [str(arg) for arg in reversed(self.data_stack[-arity:])]
self.data_stack = self.data_stack[:-arity]
result = '{' + ', '.join(map(str, tuple_args)) + '}'
self.data_stack.append(result)
Any other suggestions for improvement?
- andybak 5y agoMy personal rule is to use comprehensions when they improve readability and to avoid them when they don't. There's usually a threshold where I go "nope" and unroll it into a good old loop. But when you're in their sweet spot, they definitely improve readability.
- michaelhoffman 5y agoelif cmd.op == 'TUPLE': arity, = cmd.args stack = self.data_stack text = ', '.join(str(stack.pop()) for _ in range(arity)) stack.append(f'{{{text}}}')