Replacing Values In Csv By Using Python
def update(all_marks, stud_num, mark, column, result): lines = [l for l in all_marks] for row in all_marks: if stud_num in row: lines[rows][column] = m
Solution 1:
Here is a modified version of your function that will return the output as expected:
defupdate(all_marks, stud_num, mark, column):
for i inrange(len(all_marks)):
if stud_num in all_marks[i]:
all_marks[i][column] = mark
return all_marks
And here is how it works:
>>> marks[['a', '', '', '', '', ''], ['b', '', '', '', '', ''], ['c', '', '', '', '', ''], ['d', '', '', '', '', ''], ['e', '', '', '', '', ''], ['f', '', '', '', '', ''], ['g', '', '', '', '', '']]
>>> update(marks,'a','10',2)
[['a', '', '10', '', '', ''], ['b', '', '', '', '', ''], ['c', '', '', '', '', ''], ['d', '', '', '', '', ''], ['e', '', '', '', '', ''], ['f', '', '', '', '', ''], ['g', '', '', '', '', '']]
Note that marks
is now modified
>>> marks[['a', '', '10', '', '', ''], ['b', '', '', '', '', ''], ['c', '', '', '', '', ''], ['d', '', '', '', '', ''], ['e', '', '', '', '', ''], ['f', '', '', '', '', ''], ['g', '', '', '', '', '']]
If you want to change that so that update simply returns a copy of modified data change the function in the following way:
def update(all_marks, stud_num, mark, column):
tmp =all_marks
for i in range(len(tmp)):
if stud_num in tmp[i]:
tmp[i][column] = mark
return tmp
Solution 2:
Here is the working code:
def update(all_marks, stud_num, mark, column, result):
lines = [l for l in all_marks]
forrowinrange(len(all_marks)):
if all_marks[row][0] == stud_num:
lines[row][column] = mark
And here are the explanations:
for row in range(len(all_marks)):
=> you don't want to iterate over list objects (e.g. ['a','','','','','']) but over list indices
ifstud_num== all_marks[row][0]:
=> This is to check only the first character of your row, not any character.
lines[row][column] = mark
=> typo here, should be row and not rows
Solution 3:
Looping on the row indices isn't as efficient as looping on the rows themselves. A more pythonic way would be
def update2(all_marks,stud_num,mark,column):
forrowin all_marks:
if stud_num inrow:
row[column] = mark
return all_marks
Post a Comment for "Replacing Values In Csv By Using Python"