I'm a beginner. I'd like to know how many times in a row the 0.1.2.3rd in each of the two-dimensional lists in Python until None appears, and how to program the reset when None appears.
Input:
listA=[0,-1,1,0],
[1, 0, -1, 1],
[0, 1, None, 1],
[-1, None, 0, 1]
Output:
[4,0,1,4]
In this way, the number 0 in the list continued four times in a row, so I would like to print 4 times in a row, 4 times in a row, 0 times in a reset, and 4 times in a row without a single.Thank you for your cooperation.
python
>>[i[::-1].index(None) if None in self(i) for i in zip(*listA)]
[4, 0, 1, 4]
0
each time None
appearsIf you think about it the other way around,
0
appearsis the case.The latter should be as efficient as the algorithm can omit the subsequent count when 0
.If you write this, for example, it will look like this:
listA=[0,-1,1,0],
[1, 0, -1, 1],
[0, 1, None, 1],
[-1, None, 0, 1]
width=len(listA[0])
height=len(listA)
result=[0]*width
# Count up from 0 to (width-1)
for win range (width):
# Countdown from (height-1) to 0
for hin range (height-1, -1, -1):
# Stop the current count when None appears.
if listA[h][w] == None:
break
result[w]+=1
print(f"{result=}")
I wrote down the numbers in a function, and I wrote down the parts that I looked up vertically (in a column).
listA=[0,-1,1,0],
[ 1, 0, -1, 1],
[0, 1, None, 1],
[-1, None, 0, 1]
defcnt(lst):
n = 0
for vinst:
n = 0 if v is None elsen + 1
return n
result = [cnt([listA[i][j]] for i in range (len(listA))])
for jin range (len(listA[0]))]
print(result)
[4,0,1,4]
© 2025 OneMinuteCode. All rights reserved.