I have a list of values in a column (A) and want to increment by 1 in column (B) until the value in A changes, however, having difficulty in my loop to reset the increment when A changes.
JavaScript
x
13
13
1
B = []
2
list_length = len(A)
3
4
for i in range(0, list_length):
5
j = 1
6
while A[i] == A[i+1]:
7
B = j
8
j += 1
9
i += 1
10
else:
11
B = 1
12
j += 1
13
Here is desired output:
Product(A) | No.(B) |
---|---|
Apple | 1 |
Apple | 2 |
Apple | 3 |
Orange | 1 |
Orange | 2 |
Orange | 3 |
Orange | 4 |
Orange | 5 |
Orange | 6 |
Melon | 1 |
Melon | 2 |
Peach | 1 |
Peach | 2 |
Peach | 3 |
Peach | 4 |
Advertisement
Answer
The other two answers are awesome, but I was initially stuck to follow your initial approach with the counter, so here’s what I did:
JavaScript
1
18
18
1
from prettytable import PrettyTable
2
3
fruit_table = PrettyTable(["Product(A)", "No.(B)"])
4
5
products = ["Apple", "Apple","Apple", "Orange","Orange","Orange","Orange","Orange","Melon","Melon", "Peach","Peach","Peach"]
6
7
counter = 0
8
for i in range(0, len(products)-1):
9
10
if products[i] == products[i+1]:
11
counter+= 1
12
fruit_table.add_row([products[i],counter])
13
else:
14
fruit_table.add_row([products[i],counter+1])
15
counter=0
16
17
print(fruit_table)
18
Output:
JavaScript
1
17
17
1
+------------+--------+
2
| Product(A) | No.(B) |
3
+------------+--------+
4
| Apple | 1 |
5
| Apple | 2 |
6
| Apple | 3 |
7
| Orange | 1 |
8
| Orange | 2 |
9
| Orange | 3 |
10
| Orange | 4 |
11
| Orange | 5 |
12
| Melon | 1 |
13
| Melon | 2 |
14
| Peach | 1 |
15
| Peach | 2 |
16
+------------+--------+
17