Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"python way" to parse and conditionally replace every element in 2D list [duplicate]

I have a list which consists of further lists of strings which may represent words(in the alphanumeric sense) or ints, e.g.

myLists = [['5','cat','23'], 
           ['33','parakeet','scalpel'], 
           ['correct','horse','battery','staple','99']]  

I want to parse the array so that all integer representations are converted to ints. I have a simple function, numParser(string) to this end:

def numParser(s):
    try:
        return int(s)
    except ValueError:
        return s

With my c/java background I would normally just iterate through both arrays, changing each value (the fact that those arrays would be homogeneous notwithstanding). But I'm new to python and thought there might be a better way to do this, so I searched around and found a couple SO posts regarding map() and list comprehension. List comprehension didn't seem like the way to go because the lists aren't uniform, but map() seemed like it should work. To test, I did

a=['cat','5','4']
a = map(numParser, a)

Which works. Without thinking, I did the same on a nested loop, which did not.

for single_list in myLists:
    single_list = map(numParser, rawData)

Now, after receiving an unchanged 2D array, it occurs to me that the iterator is working with references to the array, not the array itself. Is there a super snazzy python way to accomplish my goal of converting all integer representations to integers, or do I need to directly access each array value to change it, e.g. myLists[1][2] = numParser(myLists[1][2])?

like image 997
Daniel B. Avatar asked Apr 01 '26 04:04

Daniel B.


1 Answers

You can do this with list comprehension:

>>> [map(numParser, li) for li in myLists]
[[5, 'cat', 23], [33, 'parakeet', 'scalpel'], ['correct', 'horse', 'battery', 'staple', 99]]
like image 101
Rohit Jain Avatar answered Apr 02 '26 19:04

Rohit Jain



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!