Home > Software engineering >  Apply function to a specific element of tuples in a list
Apply function to a specific element of tuples in a list

Time:06-22

I have a list of tuples and would like to modify (using a function) a specific element of each tuple in the list.

lst = [('a', 'b', 'c32@', 45), ('e', 'f', 'g812', 22)]

Ideally, my function should extract number from the text in [2] and return the list but with the third element modified.

So far I have tried using map and lambda together which only returns a list of the extracted number. Here is my attempt:

def extract_num(txt):
    # do sth
    return num

new_lst = list(map(lambda el: extract_num(el[2]), lst))

Note: I cannot modify the extract_num func to take a tuple as argument since it is used somewhere else without a tuple.

CodePudding user response:

What about using another function the whole modification logic that uses your extract_num function?

def extract_num(txt):
    return 'x'

def alter_tuple(t, pos=2):
    return t[:pos] (extract_num(t[pos]),) t[pos 1:]

new_lst = [alter_tuple(t) for t in lst]

print(new_lst)

output: [('a', 'b', 'x', 45), ('e', 'f', 'x', 22)]

CodePudding user response:

Do you mean it?

def trim(sentence):
    return int(''.join([str(element) for element in sentence if element.isnumeric()]))

print(trim('sdf2dsfd54fsdf'))
>>> 254
print(list(map(lambda el: trim(el[2]), lst)))
>>> [32, 812]
  • Related