-1
x = [[-123 456],[567 -8910],[432 -890], [-567 976]]

I have a list of list, I want to swap the negative symbol of x and y elements of a list, if x is not negative it should be changed into negative and if y is negative it should be changed into positive (just have to change the symbol).

It should be like this:

x = [[-123 456],[-567 8910],[-432 890], [-567 976]]

I also want to extract all of the x elements in a separate list (for example: u = [-123,-567,-432,-567]) and y elements in a separate list (for example: v = [456, 8910, 980, 976]). Please suggest possible solutions.

The issue that I'm facing is that there are no commas between the elements

devopio
  • 15
  • 3

3 Answers3

2

Basically you want all x to be negative and all y to be positive. abs can be very useful here. No need to check if negative or not.

data = [[-123, 456], [567, -8910], [432, -890], [-567, 976]]

output = [[-abs(x), abs(y)] for x, y in data]

And to get all of x and all of y in a list is another simple comprehension just exclude the value you don't want.

all_x = [x for x, y in data]
all_y = [y for x, y in data]
Jab
  • 26,853
  • 21
  • 75
  • 114
  • `abs()` always returns positive numbers. `-abs(x)` when `x` is `-123` will be `-123`. You're not flipping the sign. – Barmar Jan 21 '21 at 01:15
  • @barmar Correct. They don't want it flipped in that situation. – Jab Jan 21 '21 at 01:38
  • I see, I didn't understand that the rule was different for x and y. Thought they just wanted to flip everything. – Barmar Jan 21 '21 at 05:00
0

Pretty simple if you are able to use numpy:

import numpy as np

x = np.array([[-123, 456],[567, -8910],[432, -890], [-567, 976]])
out = np.abs(x) * [-1, 1]

print(out)

Result:

> [[-123  456]
 [-567 8910]
 [-432  890]
 [-567  976]]

To split into separate arrays, simply use array slicing:

xArr = out[:,0]
yArr = out[:,1]
Zock77
  • 951
  • 8
  • 26
  • The output for last list is incorrect. It should be [-567, 976] according to OP. – itsDV7 Jan 21 '21 at 00:34
  • I think it must be a typo in the OP's example as that doesn't seem to match his requirements – Zock77 Jan 21 '21 at 00:41
  • The main issue is that there are no commas in between the elements, that is why I'm getting error everytime, – devopio Jan 21 '21 at 00:42
  • Example is correct, we just need to shift the negative symbol from the second element to the first – devopio Jan 21 '21 at 00:43
0
import numpy as np
data = np.array([[-123, 456],[567, -8910],[432, -890], [-567, 976]])

# Negative-Number
for i in range(data.shape[0]):
  if(data[i][0]>0):
    data[i][0] = data[i][0]*-1
  if(data[i][1]<0):
    data[i][1] = data[i][1]*-1

# Store results
all_x = [x for x, y in data]
all_y = [y for x, y in data]

Output:

print("Output:\n",data)
print("all_x:\n",all_x)
print("all_y:\n",all_y)

Output:
 [[-123  456]
 [-567 8910]
 [-432  890]
 [-567  976]]
all_x:
 [-123, -567, -432, -567]
all_y:
 [456, 8910, 890, 976]
itsDV7
  • 854
  • 5
  • 12