Penguin
Penguin

Reputation: 2431

Get the distance from every element in a list to any other element

I have a list:

l  = [10,22,3]

I'm trying to create a function that returns the distances (how close they are in the list itself), such that elements on the left of any element has a negative value, and those on its right has a positive value:

#optimal output
dis = [[0,1,2],[-1,0,1],[-2,-1,0]]

Is there a quick way to do that?

Upvotes: 1

Views: 1185

Answers (2)

Alejandro Condori
Alejandro Condori

Reputation: 864

Based on Leonardo's answer, to do what the OP commented:

nums = [10, 22, 3]
distances = []

for i in range(len(nums)):
    temp = []
    for n in range(len(nums)):
        temp.append(n-i)
    distances.append(temp)
print(distances)

Output:

[[0, 1, 2], [-1, 0, 1], [-2, -1, 0]]

Upvotes: 2

Leonardo
Leonardo

Reputation: 292

You could try a nested for-in loop. The idea here is to just retrieve the indexes of each value and its distance from other values.

nums = [10, 22, 3]
distances = []

for i in range(len(nums)):
    for n in range(len(nums)):
        distances.append(i-n)

print(distances)

Output:

[0, -1, -2, 1, 0, -1, 2, 1, 0]

Also, never name a variable l, because it looks like a 1.

Upvotes: 3

Related Questions