Replacing The Old Numbers In A List With New Numbers And Create A New Array
Solution 1:
Right now you are only appending the values to the updated list that have been changed. Instead, you want to append all values, while updating the values that need to be added to. Here's a form using your existing columns with a list comprehension:
colB = [32.0, 5.0, 12.0, 1.0, 87.0, 9.0]
colD = ['add10', 'add10', '', '', '', 'add10']
update_colB_values = [B + 10 if D == 'add10' else B for B, D in zip(colB, colD)]
# [42.0, 15.0, 12.0, 1.0, 87.0, 19.0]
You should be able to replace your instantiation and for
loop with this line.
It should be noted that the built-in zip
is a very useful function that you may be able to utilize in your earlier code. For example, it's base behavior is to "tranpose" a 2D list.
matrix = [['a1', 'a2', 'a3'],
['b1', 'b2', 'b3'],
['c1', 'c2', 'c3']]
forrowin zip(*matrix):
print(list(row))
# ['a1', 'b1', 'c1']
# ['a2', 'b2', 'c2']
# ['a3', 'b3', 'c3']
The function zip
takes an arbitrary number of positional arguments and matches all the ith
elements together. As soon as one of the rows is exhausted, iteration ends, so zip_longest
(Python 3) or izip_longest
(Python 2) from itertools
is useful if you want to pad.
To do this using your existing code, you can add an else
statement so that you include the elements that don't need 10 added to them.
update_colB_values = []
for i inrange(3,sh1.nrows):
if sh1.cell(i,3).value == "add10":
add = (sh1.cell(i,1).value) + 10
update_colB_values.append(add)
else: # addvalue = sh1.cell(i,1).value# these
update_colB_values.append(value) # lines
Post a Comment for "Replacing The Old Numbers In A List With New Numbers And Create A New Array"