简体   繁体   中英

Concatenate strings from a loop

Python beginner here! My goal is to achieve an array or a set of strings of this shape:

layer[1] = level[1].x1
layer[2] = level[1].x2
layer[3] = level[1].T
layer[4] = level[2].x1
layer[5] = level[2].x2
layer[6] = level[2].T
layer[7] = level[3].x1
...

I created the following loops to create the parts of the strings like this:

layers = 36
levels = 12
states = 12

for count_layers in range(1,37):
    print("layer["+str(count_layers)+"]=level[")

for count_levels in range(1,13):
    print(""+str(count_levels)+"].")
    print(""+str(count_levels)+"].")
    print(""+str(count_levels)+"].")

for states in range(1,13):
    print("x1")
    print("x2")
    print("T")

Now I'm asking myself how to concatenate all those parts together, so that the described set of strings can be printed out. I tried to create an array, append the values, create a numpy array, transpose it and stacked the three array parts, but this didn't work out as I got the wrong array:

  ['layer[1]=level['
  'layer[2]=level['
  'layer[3]=level['
  'layer[4]=level['
  'layer[5]=level['
  'layer[6]=level['
  'layer[7]=level['
  ...
  '1].' '1].' '2].' '2].' '2].' '3].' '3].' '3].' '4].' '4].' '4].'
  ...
  'x1' 'x2' 'M' 'x1' 'x2' 'M' 'x1' 'x2' 'M' 'x1' 'x2' 'M' 'x1' 'x2' 'M'
  ...]

Is there an elegant way to do this?

You can do this with creative string formatting and modulo / floordiv operation:

for k in range(0,90):
    print("layer[{}] = level[{}].{}".format(k+1, (k//3)+1, ["x1","x2","T"][k%3]) )

The floordiv is used for the level- number , the modulo to index into a "suffix-list" providing one of ["x1","x2","T"] .

Output:

layer[1] = level[1].x1
layer[2] = level[1].x2
layer[3] = level[1].T
layer[4] = level[2].x1
layer[5] = level[2].x2
layer[6] = level[2].T
...snipp...
layer[88] = level[30].x1
layer[89] = level[30].x2
layer[90] = level[30].T

Python 3.6+ string interpolation:

print(f"layer[{k+1}] = level[{k//3}].{['x1','x2','T'][k%3]}")                           

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM