Home > Enterprise >  How to update variables within a two-dimensional list?
How to update variables within a two-dimensional list?

Time:10-13

How to update variables within a two-dimensional list?

I'm fairly new to programming and python, I have a task to only update the variables given to me in a two-dimensional list. The sublists contain a grade and a name each. I'm supposed to update two variables given to me, every time a certain name or number appears in any of the sublists.

I've tried a few different ways of getting the the variable to update, but none of the ways I've tried have resulted in a correct answer. So if anyone could help to answer how to get to the elements in the sublists and go through them correctly?

The code that I ended up stuck with

grades = [['John', 2], ['Chris', 4], ['Morgan', 4], ['John', 2], ['Morgan', 2], ['Richard', 1], ['Sam', 2], ['Richard', 1], ['Morgan', 0], ['Cecilia', 2], ['Richard', 1], ['Sam', 2], ['Sam', 2], ['John', 4], ['Sam', 0]]
fours = 0
johns = 0
f = 4
for i in range(len(grades)):
    sub_list = grades[i]
    for f in range(len(sub_list)):
        fours  =1
    for 'John' in range(len(sub_list)):
        johns  =1

CodePudding user response:

If you need to update when those values occur, you will need to make a decision somewhere with if.

You can also streamline this by not using indexes, but directly iterating.

grades = [['John', 2], ['Chris', 4], ['Morgan', 4], ['John', 2], ['Morgan', 2], ['Richard', 1], ['Sam', 2], ['Richard', 1], ['Morgan', 0], ['Cecilia', 2], ['Richard', 1], ['Sam', 2], ['', 2], ['John', 4], ['Sam', 0]]
fours = 0
johns = 0

for lst in grades:
  if lst[0] == 'John': johns  = 1
  if lst[1] == 4: fours  = 1

CodePudding user response:

It looks like you are on the right track, but there are some syntactical errors. When you are iterating within the sublists, you'd want to check for equality with an if statement:

def main():
    grades = [['John', 2], ['Chris', 4], ['Morgan', 4], ['John', 2], ['Morgan', 2], ['Richard', 1], ['Sam', 2], ['Richard', 1], ['Morgan', 0], ['Cecilia', 2], ['Richard', 1], ['Sam', 2], ['', 2], ['John', 4], ['Sam', 0]]
    fours = 0
    johns = 0
    for i in range(len(grades)):
        sub_list = grades[i]
        for i in range(len(sub_list)):
            if sub_list[i] == 4:
                fours  = 1
            if sub_list[i] == 'John':
                johns  = 1
    print(fours)
    print(johns)

main()

Regards

  • Related