简体   繁体   中英

How to convert negative values to positive in a list of tuples?

I have a list of tuples like that:

tuple_list =  [(1, -1), (3, 0), (3, -2), (-1, -3)]

I need to convert all elements in positive values like that:

tuple_list1 =  [(1, 1), (3, 0), (3, 2), (1, 3)]

And finally I want to sum each element inside a tuple:

tuple_list2 =  [(2), (3), (5), (4)]

Could someone hellp me please?

You just need to map abs to each element in your tuples to get them to be positive. Note that (2) is not a tuple, (2,) is a tuple.

tuple_list =  [(1, -1), (3, 0), (3, -2), (-1, -3)]
[(sum(map(abs, el)),) for el in tuple_list]

Output: [(2,), (3,), (5,), (4,)]

tuple_list =  [(1, -1), (3, 0), (3, -2), (-1, -3)]
[sum(map(abs, el)) for el in tuple_list]

Output: [2, 3, 5, 4]

You can simply do the list comprehension to iterate over the values to convert them into positive values and applying sum over the list of positive values and then atlast converting the result into a tuple.

tuple_list =  [(1, -1), (3, 0), (3, -2), (-1, -3)]
result = [(sum([abs(a) for a in x]),) for x in tuple_list]
print(result)

Output:

[(2,), (3,), (5,), (4,)]

Try this :

tuple_list =  [(1, -1), (3, 0), (3, -2), (-1, -3)]
tuple_list2 = [(sum(map(abs, sl)),) for sl in tuple_list]

Output :

[(2,), (3,), (5,), (4,)]

tuple_list2 = [sum(map(abs, sl)) for sl in tuple_list] should produce [2, 3, 5, 4] output.

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