You can use
absandmapfunctions like thismyList = [2,3,-3,-2] print(list(map(abs, myList)))
Output
[2, 3, 3, 2]
Or you can use list comprehension like this
[abs(number) for number in myList]Or you can use list comprehension and a simple if else condition like this
[-number if number < 0 else number for number in myList]
You can use
absandmapfunctions like thismyList = [2,3,-3,-2] print(list(map(abs, myList)))
Output
[2, 3, 3, 2]
Or you can use list comprehension like this
[abs(number) for number in myList]Or you can use list comprehension and a simple if else condition like this
[-number if number < 0 else number for number in myList]
A list comprehension would also work:
>>> lst = [2,3,-3,-2]
>>> [abs(x) for x in lst]
[2, 3, 3, 2]
>>>
Videos
The problem is with the loop you are using , Trying modifying it this way
def abs1(array):
for i in range(len(array)):
if array[i] < 0:
array[i] = array[i] * (-1)
print(array)
The reason is the loop you were previously using was just for accesing list elements but not giving you reference to change anything in list I solved it with using indexes on list.
Try :
import numpy as np
array= ...
np.abs(np.array(array))
numpy is very powerful and fast, learn to use it asap.
EDIT since the problem is how to do a function on each element of a list and wrap those results in a list of the same length :
Two solutions come to mind :
- hardcore python style :
[x if x<0 else -x for x in array]
the brackets say I want a list, inside I write the function and I say where to find the parameters to my function.
[abs(x) for x in array]
[f(x) for x in array] # for any defined f that can handle every element of array
- map(lambda x : f(x), array)
you create a mapping on the elements of array. To those elements, you apply lambda. lambda is a way to define a function locally, very locally.
list(map(lambda x : abs(x),array))
finally you make a list from the mapping, to retrieve the result. If you don't, it will stay as an abstract, the definition of a relation between array and something that is yet to be instantiated.
You can do it like this:
A = [2, 7, 5, 9, 3, 1, 2]
temp = sorted(A)
min_diff = min([abs(i - j) for i, j in zip(temp [:-1], temp [1:])])
print(min_diff) # -> 0
Sorting makes sure that the element pair (i, j) which produce the overall smallest difference would be a pair of consecutive elements. That makes the
number of checks you have to perform much less than the brute force approach of all possible combinations.
Something a bit more clever that short-circuits:
A = [2, 7, 5, 9, 3, 1, 2]
def find_min_diff(my_list):
if len(set(my_list)) != len(my_list): # See note 1
return 0
else:
temp = sorted(my_list)
my_min = float('inf')
for i, j in zip(temp [:-1], temp [1:]):
diff = abs(i - j)
if diff < my_min:
my_min = diff
return my_min
print(find_min_diff(A)) # -> 0
Notes:
1: Converting to set removes the duplicates so if the corresponding set has less elements than the original list it means that there is at least one duplicate value. But that necessarily means that the min absolute difference is 0 and we do not have to look any further.
I would be willing to bet that this is the fastest approach for all lists that would return 0.
You should not be subtracting 1 from j in the inner loop as you end up skipping the comparison of the last 2. It is better to make the adjustments in the loop ranges, rather than subtracting 1 (or not) in the loop code:
A = [2, 7, 5, 9, 3, 1, 2]
N = 7
mint = 1000
for i in range (0, N-1):
for j in range (i+1, N):
if (abs(A[i] - A[j]) < mint):
mint = abs(A[i] - A[j])
print(i, j)
print(mint)
print(mint) # 0
I have also avoided the use of a built-in function name min.
To avoid the arbitrary, magic, number 1000, you can perform an initial check against None:
A = [2, 7, 5, 9, 3, 1, 2]
N = 7
mint = None
for i in range (0, N-1):
for j in range (i+1, N):
if mint is None:
mint = abs(A[i] - A[j])
elif (abs(A[i] - A[j]) < mint):
mint = abs(A[i] - A[j])
print(i, j)
print(mint)
print(mint) # 0
A cleaner example I think:
a=[['2.40', '1970-1990', 'Austria']]
b = []
for i in a[0]:
try:
b.append(abs(float(i)))
except:
b.append(i)
print(b)
[2.4, '1970-1990', 'Austria']
a = ['2.40', '1970-1990', 'Austria'] #your old list (with the extra [] removed, they seem not to have a point... If you need them you can easily edit the code appropriately)
b = [] #a new list with the absolute values
for i in range(0, len(a)): #going through each of the values in a
try:
b += [abs(float(a[i]))] #trying to take the absolute value and put it in the new list (I have the float() because it appears that your 2.40 is a string. If you have it as an actual integer or float (such as 2.40 instead of '2.40') you can just use abs(a[i])
except:
b += [a[i]] #if taking the absolute value doesn't work it returns the value on its own.
print(b)