Home > Enterprise >  How to input to differant multiple lists using one loop in pthon
How to input to differant multiple lists using one loop in pthon

Time:05-05

Hi im kinda new to python and i have a question that i cant find any answer for that.

ok, imagine we have 5 students and we want to take their scores in 3 lessons (e.g., math, science, geography) and we have empty lists named by these lessons, i want to know how can we input their scores in this lists using one loop and not by writing the code one by one for this lists. scores inputs be like

80 90 95 40 70
70 50 60 50 50
80 90 90 80 80

thes are our lists:

    math = science = geography =[]

and i know how to input multiple variables:

[int(x) for x in input().split()]

i tried to use 'for' like below but it doesnt work cause it gives 'i' equal amount of lists but does not copy the results to list.

i = []
for i in math, science, geography:
        i = [int(x) for x in input().split()]

so please help me if you can, thanks.

CodePudding user response:

d ={}
for i in ['math', 'science', 'geography']:
        d[i] = [int(x) for x in input().split()]

You can simply store it in a dictionary where the dictionary keys are the subjects and the items are lists containings marks obtained by students.

{'math': [1, 2, 3, 4, 5], 'science': [6, 7, 8, 9, 0], 'geography': [1, 2, 3, 4, 5]}

OR

If you have 3 separate lists prepared and want to populate those, you can simply do this

subject_lists = []
for i in ['math', 'science', 'geography']:
        subject_lists.append([int(x) for x in input().split()])

Now subject_lists contains all the lists in order. If you have some order specified somewhere that first list is for subject 1 and second for subject 2 you can use it easily.

   subject_map = {
     'math':0,
     'science':1,
     'geo':2
   }

So now if you have to access the subject math to get the scores achieved by students, you can simply think like this

subject_index = subject_map['math']
math_scores = subject_lists[subject_index ]

CodePudding user response:

2 problems:

1. math = science = geography = [] - this will assign the same reference to all the variables. Which means every change you do on one of the lists will be reflected in other ones.

2.

for i in math, science, geography:
        i = [int(x) for x in input().split()]

Here you are changing the reference i points to when you assign new list to it, thus making it no longer the same thing each of math, science, geography are. You need to edit each of the given lists in-place. With those two things in mind, if you rewrite your code like so, it will work:

math = []
science = []
geography = []
for i in math, science, geography:
        i.extend([int(x) for x in input().split()])
  • Related