Home > Net >  Apply a function on a single element of a tuple
Apply a function on a single element of a tuple

Time:10-18

With a direct example it would be easier to understand

data = [(1995, 50.28), (1996, 28.52)]
result = [(1995, 50), (1996, 29)]

I would like to apply a transformation only on the second number of each tuple (50.28 and 28.52).

I saw the map() function that could help, but i think it works only on ALL elements, and having tuples inside list makes it a bit tricky

CodePudding user response:

The more intuitive solution would be to iterate through the elements of the list, as many other answers noticed.

But if you want to use map, you can indeed but you need first to define a function that applies your desired transformation to the second element of each tuple:

data = [(1995, 50.28), (1996, 28.52)]

def round_second(tup):
    return tup[0], round(tup[1])

result = list(map(round_second, data))
result
>>> [(1995, 50), (1996, 29)]

CodePudding user response:

You can use basic "for" loop. You can use like that;

data = [(1995, 50.28), (1996, 28.52)]

for i in range(0,len(data)):
    data[i] = list(data[i])
    data[i][1] = round(data[i][1])
    data[i]=tuple(data[i])

CodePudding user response:

You can do this with a list comprehension and the built-in round() function as follows:

data = [(1995, 50.28), (1996, 28.52)]

result = [(x, round(y)) for x, y in data]

print(result)

Output:

[(1995, 50), (1996, 29)]

CodePudding user response:

You can use lambda function inside map like this:

result = list(map(lambda x:(x[0], round(x[1])), data))
Output is :

[(1995, 50), (1996, 29)]

CodePudding user response:

Map is what you need. Use it to apply a function on each tuple. That function would only interact with the second number of each tuple

def function(item):
    whatever(item[1])
    return item

data = [(1995, 50.28), (1996, 28.52)]
map(function, data)
  • Related