vendredi 4 mai 2018

Applying a single condition to a number of elements with different results

Suppose I have the following code:

if not dims:
  dims = [0] * iterations
if not counts:
  counts = [0] * iterations
if not grids:
  grids = [0] * iterations

But this doesn't look very pretty, and I was wondering if I could compress it a bit but also find the fastest algorithm (although I barely know anything about algorithm speed). The ideal solution would be if I could do something like this:

val = [0] * iterations if not val for val in (dims, counts, grids)

but I know I can't do that, so a similar code I thought would work would be:

if not val for val in (dims, counts, grids):
  val = [0] * iterations

but I can't do that either and even if I could, wouldn't it check every item in (dims, counts, grids) and then assign a single variable val to the value (list) [0] * iterations?

I was wondering if there was a better way to do it than:

for val in (dims, counts, grids):
  if not val:
    val = [0] * iterations

My actual code, though, has:

if not grids:
  grids = [[0]] * iterations

so

for val in (dims, counts, grids):
  if not val:
    if val == grids:
      val = [[0]] * iterations
    val = [0] * iterations

would only be an improvement in one line. Is there any way to do it combining (dims, counts, grids) with ([0], [0], [[0]]) to reduce the lines it takes?

Please keep in mind I'm (relatively) new to python (and StackOverflow) so most of the things I find or read in the docs are very difficult to understand.

Aucun commentaire:

Enregistrer un commentaire