-2

Let's say I have 3 lists

a = [1.12, 2.23, 3.34]
b = [2.12, 3.23, 4.34]
c = [3.12, 4.23, 5.34]

my goal is to round the numbers down to 1 decimal. so I have this custom function:

import math
def round_down(n, decimals=0):
    multiplier = 10 ** decimals
    return math.floor(n * multiplier) / multiplier

May I ask what is the most efficient way of operating on each element in each object? In this easy example I could write a loop for each of the 3 objects, such as:

for i in np.range(len(a)):
    a[i] = round_down(a[i], decimals=1)

However, in my work, I have many more lists of various lengths and I really don't want to code them one by one. Is there a way to iterate through a list of objects? or process them in parallel?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Jerry Fan
  • 105
  • 6

2 Answers2

0

Just like you use a for loop to avoid coding for every single element, use a for loop to iterate over all your lists:

my_lists = [a, b, c]
for l in my_lists:
    for i in np.range(len(l)):
        l[i] = round_down(l[i], decimals=1)
Julien
  • 13,986
  • 5
  • 29
  • 53
  • I would shove that in a double list comprehension for better speed. – Guimoute Dec 23 '19 at 00:13
  • @Guimoute Not sure how you would make it a double, but here's a single: `l[:] = [round_down(x, decimals=1) for x in l]` – wjandrea Dec 23 '19 at 00:25
  • Small typo--should be np.arange rather than np.range (otherwise AttributeError: module 'numpy' has no attribute 'range'). But not sure why you're not using the built-in range function since it should be [faster in this particular case](https://stackoverflow.com/questions/10698858/built-in-range-or-numpy-arange-which-is-more-efficient) – DarrylG Dec 23 '19 at 04:35
  • @wjandrea Something like `my_rounded_lists = [[round_down(x, 1) for x in lst] for lst in my_lists]` I believe. I can't test from here. – Guimoute Dec 26 '19 at 12:12
0
combine_array = [a, b, c]
for p in combine_array:
    for i in np.range(len(p)):
        p[i] = round_down(p[i], decimals=1)
  • 3
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. I would recommend you to check SO's [official How to Answer article](https://stackoverflow.com/help/how-to-answer) along with the comprehensive [blog post](https://codeblog.jonskeet.uk/2009/02/17/answering-technical-questions-helpfully/) from [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet). – Aleksey Potapov Dec 23 '19 at 08:29