简体   繁体   中英

Apply function to a specific element of tuples in a list

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.

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM