Skip to content Skip to sidebar Skip to footer

"python Way" To Parse And Conditionally Replace Every Element In 2d List

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

Solution 1:

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]]

Solution 2:

Here is one way to do it:

for single_list in myLists:
    for i, item in enumerate(single_list):
        single_list[i] =numParser(item)

The advantage of this method is you actually replace the elements in the existing lists, not creating new lists.

Solution 3:

You can use a nested list comprehension and use str.isdigit() method to check of your string is a digit, then convert it to int:

>>> [[int(i) if i.isdigit() else i for i in j] for j in myLists]
[[5, 'cat', 23], [33, 'parakeet', 'scalpel'], ['correct', 'horse', 'battery', 'staple', 99]]

Or if you want to use your function you can pass it to map function or use in a list comprehension.

Solution 4:

defnumParser(string):
    try:
        returnint(string)
    except ValueError:
        return string

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

    printlist(map(numParser, _list) for _listin myLists)


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

Post a Comment for ""python Way" To Parse And Conditionally Replace Every Element In 2d List"