Issue
I've got a list of numbers and I'm trying to loop through the list and change each number depending on a certain criteria. But my code doesn't change the list, its still the same when I print it again at the end. My code is below:
list = [[10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0]]
for x in list:
if (x >= 0):
x = 100
if (x < 0):
x = -100
print list
Looked at this and didnt solve the problem Looping over a list in Python
Solution
You've got two problems: one, your list is actually a list of lists; two, you are not assigning values to your list properly. Try something like this:
# Loop over the indices of the list within the list
for i in range(len(list[0])):
if (list[0][i] >= 0):
list[0][i] = 100
else:
list[0][i] = -100
print list
There are ways to make this more efficient and generalizable, but keeping your for
loop style, the above code would work in your case.
For instance, you can also do this (essentially the same thing in list iteration form, and looping through each list in your list of list, in case you had more than just one):
[[100 if lst[i] >=0 else -100 for i in range(len(lst))] for lst in list]
for a list of multiple lists, this works as such:
old = [[10.0, 4.0, 10.0, 10.0, 4.0, 0.0, 10.0, 10.0, 10.0, 4.0, 6.0],[-2, 2, -2]]
new = [[100 if lst[i] >=0 else -100 for i in range(len(lst))] for lst in old]
>>> new
[[100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100], [-100, 100, -100]]
Also, it is generally bad style to call your list list
, as list
is already a built-in type in python.
Answered By - sacuL
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.