创建具有两个不同数字的列表

时间:2014-06-04 01:06:27

标签: python python-3.x

我有两个号码xy。 例如x为1.5,y为1.5 我需要创建一个包含8个不同值的列表列表。

[[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.

如何使用不同的x和y值在python 3中执行此操作? xy将始终为1到10之间的数字。但它们将为1.5或2.5或3.5等。

3 个答案:

答案 0 :(得分:1)

尝试使用以下列表理解:

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

因此:

>>> 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]]
>>> 

编辑:

或者,如果列表理解太混乱,您可以将其更改为嵌套的for循环:

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

运行如下:

>>> 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]]
>>> 

答案 1 :(得分:0)

试试这个:

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

输出:

[[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 :(得分:0)

查看this question

要从列表中删除:

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)

请注意,如果list_to_remove不在list_of_lists,则会引发异常。要抓住这个,你需要:

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))