Python joining vertical lists

I have this, for example, the following characters:

.....U...... L...L.###### .S....#..... ....L....... 

which I saved in the list

 chars = ['.....U......', 'L...L.######', '.S....#.....', '....L.......'] 

I used this to store it in characters:

 for x in range(0, N): g = input() chars.append(g) 

Now the problem is that I want to turn all the points between the letters L into #, but vertically, and so:

 .....U...... L...L.###### .S..#.#..... ....L....... 

I’ve tried it for several hours, and I can’t think of anything. Many thanks.

EDIT: I used this to connect them horizontally. And it works.

 while y != N: modchars0 = list(chars[y]) if modchars0.count('L') == 0: y += 1 else: for k in range(0, M): if 'L' in modchars0[k]: start = k + 1 break for l in range(M-1, 0, -1): if 'L' in modchars0[l]: end = l break for h in range(start, end): if 'L' in modchars0[h]: pass else: modchars0[h] = '#' modchars1 = modchars1.join(modchars0) chars[y] = modchars1 y += 1 
+5
source share
2 answers

Like @ U2EF1 mentioned in the comments, you can take the transpose of the list with zip(*chars) , and then with regex you can convert the points between 'L' to '#'. And then at the end of zip(*) new elements will again get the desired result:

 >>> import re >>> r = re.compile(r'(?<=L).*(?=L)') >>> def rep(m): return m.group().replace('.', '#') ... >>> zipped = (r.sub(rep, ''.join(x)) for x in zip(*chars)) >>> for x in zip(*zipped): print ''.join(x) ... .....U...... L...L.###### .S..#.#..... ....L....... 
+6
source

Late answer

This one probably doesn't deserve a better answer, but is an alternative nonetheless.

First, define a function that will rotate the list horizontally and vertically:

 def invert(chars): inverted = [] for i in range(len(chars[0])): newStr="" for j in range(len(chars)): newStr+=chars[j][i] inverted.append(newStr) return inverted 

Then you can use it as follows:

 def main(): chars = ['.....U......', 'L...L.######', '.S....#.....', '....L.......'] invChars = invert(chars) for i in range(len(invChars)): invChars[i] = re.sub(r'(?<=L)(\..*?)L', lambda k: k.group().replace('.','#'), invChars[i]) chars = invert(invChars) 
+3
source

Source: https://habr.com/ru/post/1211382/


All Articles