Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special Operation on each element of array

I am trying to write out data in a very specific format including numbers, dates, strings. My input is an array containing this data but not necessarily in the right format. So I need to apply custom operations on almost every element. The input and output have variable length.

edit: A little bit more clarification here: I am parsing data from different sources with different formats. The task is to write them out to the same format. I am writing a default parser for each source. There is no way around that. I am writing the data into a format that contains all necessary fields for the output. e.g. [name, data, value, cur1, cur2, ...] Now I need to format this data in a very specific way . E.g. Add something to the name. Basically I need to modify every element in my array in a rather unique way based on the index.

The input could look something like that:

arr = ['name', 30.09.2019, 20.5, 'EUR', 'USD', ....]
# or
arr = ['name', 30.09.2019]
# or
arr = ['name', '', '', '', '', 'note', '17.5', '',....]

And then I need to apply some functions to each element. The only solution I could come up with would be:

for i in range(0, len(arr)):
   if(i == 0):
      process_zero(arr[i])
   elif(i == 1):
      process_one(arr[i])
   ...

If it wasn't variable length I could do something like this:

process_zero(arr[0])
process_one(arr[1])
...

Is there a better/cleaner way to do this?

like image 445
Julian Avatar asked Jan 25 '26 22:01

Julian


1 Answers

Since the array is variable length, it sounds like it's not really an appropriate structure in which to put your data. Make a dictionary or a class (or for Python >=3.7, a dataclass) that contains your data in a more structured format.

# With dictionaries
sample = {'name' : 'Jane', 'USD' : 3.50, ... }

def myfunc(data_dict):
    data_dict['name'] = data_dict['name'].upper()
    data_dict['USD'] += 1
    ...

myfunc(sample)

# With classes
class MyClass:
    def __init__(self, name = '', USD = 0, ...):
        self.name = name
        self.USD = USD
        ...

    def myfunc(self):
        self.name = self.name.upper()
        self.USD += 1
        ...

sample = MyClass('Jane', 3.5, ...)
sample.myfunc()
like image 146
Zev Chonoles Avatar answered Jan 27 '26 12:01

Zev Chonoles



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!