[英]Apply a function on a single element of a tuple
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).我只想对每个元组的第二个数字(50.28 和 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我看到了 map() function 这可能有帮助,但我认为它只适用于所有元素,并且列表中有元组让它有点棘手
You can use lambda function inside map like this:您可以像这样在 map 中使用lambda function:
result = list(map(lambda x:(x[0], round(x[1])), data))
Output is: Output 是:
[(1995, 50), (1996, 29)]
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:但是如果你想使用map
,你确实可以但你需要首先定义一个 function 将你想要的转换应用于每个元组的第二个元素:
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)]
You can use basic "for" loop.您可以使用基本的“for”循环。 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])
You can do this with a list comprehension and the built-in round() function as follows:您可以使用列表理解和内置的round() function 来执行此操作,如下所示:
data = [(1995, 50.28), (1996, 28.52)]
result = [(x, round(y)) for x, y in data]
print(result)
Output: Output:
[(1995, 50), (1996, 29)]
Map is what you need. Map 就是你所需要的。 Use it to apply a function on each tuple.使用它在每个元组上应用 function。 That function would only interact with the second number of each tuple function 只会与每个元组的第二个数字交互
def function(item):
whatever(item[1])
return item
data = [(1995, 50.28), (1996, 28.52)]
map(function, data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.