-2

I have 2 numbers x and y. x for example is 1.5, and y is 1.5 I need to create a list of lists with 8 different values.

[[0.5,0.5],[0.5,1.5],[0.5,2.5],
[1.5,0.5],[1.5,1.5],[1.5,2.5],
[2.5,0.5],[2.5,1.5],[2.5,2.5]]

[1.5,1.5] #needs to be removed from the above list.

How can I do this in python 3 using different x and y values? x and y will always be numbers between 1 and 10. But they will be 1.5 or 2.5 or 3.5 etc.

user2357112
  • 260,549
  • 28
  • 431
  • 505

3 Answers3

1

Try using the following list comprehension:

items = [[a, b] for a in items for b in items if x != a or y != b]

As such:

>>> x = 1.5
>>> y = 1.5
>>> items = [x-1, x, x+1]
>>> items = [[a, b] for a in items for b in items if x != a or y != b]
>>> items 
[[0.5, 0.5], [0.5, 1.5], [0.5, 2.5], [1.5, 0.5], [1.5, 2.5], [2.5, 0.5], [2.5, 1.5], [2.5, 2.5]]
>>> 

Edit:

Or, if list comprehension is too confusing, you can just change it to nested for loops:

for i in items:
    for j in items:
        if i != x or j != y:
            cp.append([i, j])

This runs as:

>>> x = 1.5
>>> y = 1.5
>>> items = [x-1, x, x+1]
>>> cp = []
>>> for i in items:
...     for j in items:
...         if i != x or j != y:
...             cp.append([i, j])
... 
>>> items = cp
>>> items
[[0.5, 0.5], [0.5, 1.5], [0.5, 2.5], [1.5, 0.5], [1.5, 2.5], [2.5, 0.5], [2.5, 1.5], [2.5, 2.5]]
>>> 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
0

Try this:

values = [0.5, 1.5, 2.5]
[[x, y] for x in values for y in values if x <> y]

Output:

[[0.5, 1.5], [0.5, 2.5], [1.5, 0.5], [1.5, 2.5], [2.5, 0.5], [2.5, 1.5]]
Brionius
  • 13,858
  • 3
  • 38
  • 49
0

Check out this question.

To remove from a list:

list_to_remove = [x, y]
list_of_lists = [[0.5,0.5],[0.5,1.5],[0.5,2.5],
                [1.5,0.5],[1.5,1.5],[1.5,2.5],
                [2.5,0.5],[2.5,1.5],[2.5,2.5]]
list_of_lists.remove(list_to_remove)

Keep in mind that this will raise an exception if list_to_remove is not in list_of_lists. To catch this, you need:

list_to_remove = [x, y]
list_of_lists = [[0.5,0.5],[0.5,1.5],[0.5,2.5],
                [1.5,0.5],[1.5,1.5],[1.5,2.5],
                [2.5,0.5],[2.5,1.5],[2.5,2.5]]

try:
    list_of_lists.remove(list_to_remove)
except:
    print "{0} is not in list_of_lists".format(str(list_to_remove))
Community
  • 1
  • 1
Yep_It's_Me
  • 4,494
  • 4
  • 43
  • 66