I was trying to append things into a list with each set of three elements getting appended line by line. So what I mean is:
ex = [John, 20/9/21, 234
Marc, 21/9/21, 53466]
So after appending each set of 3 elements line by line. I would like to find the index of the last element of each line. So in my case, I want 234 and 53466 from this list (there will be lines and lines of these sets of three elements, so I need a general way to find them).
CodePudding user response:
If its always exactly sets of you can use array slicing
ex = ['John', '20/9/21', 234, 'Marc', '21/9/21', 53466, 'Peter', '22/9/21', 93879]
print(ex[2::3])
>> [234, 53466, 93879]
[2::3]
means start at index 2 to the end in steps of 3.
Realistically you might consider moving to 2D arrays or more advanced structures i.e. with pandas
CodePudding user response:
The trick is to append a tuple of data. That way you can treat your structure as a matrix / table.
l = []
l.append(('John' , '21/10/21' , 238))
l.append(('Marc' , '23/06/21' , 1586))
print(l)
for row in l:
print(row)
for cell in row:
print(cell)
print(l[1][1])
print(l[0][2])
Beware to NOT use l = ('...'), because if you then print out a certain index you will get that single character / number. So use l.append(...)!
I hope this is what you're looking for