两个嵌套for循环

时间:2016-01-16 15:46:06

标签: python python-2.7

我不知道如何正确地提出这个问题,但这就是我要做的事情。

public static void Robotwrite() throws Exception{
            try{
                 RobotWrite rw = new RobotWrite();            
                   rw.type("C:\\workspace\\project\\src\\main\\resources\\data\\ExampleCV.docx"); //doesnt work
                   //rw.type("C:\\Users\\Desktop\\ExampleCV.docx"); //works

                   Robot r = new Robot();
                   r.keyPress(VK_ENTER);
                   r.keyRelease(VK_ENTER);

            }catch (Exception e){
                 Log.error("Could not write");
                throw(e);
                }
            }

是否有一个简单的解决方案,所以它不会给我相同但反转的列表: 例如[2,0]和[0,2]?

我知道我可以通过列表然后删除它们但是有没有解决方案甚至没有列表? (对不起,我的英语并不完美)

4 个答案:

答案 0 :(得分:3)

您可以使用itertools.combinations

>>> from itertools import combinations
>>> list(combinations(range(3), 2))
[(0, 1), (0, 2), (1, 2)]

通过上面的例子,我们可以对range(3)中的两个元素进行任意组合,而不重复任何元素。

答案 1 :(得分:2)

当然:如果您使用y > x而不是所有可能的对添加所有对,则只会出现每对(x,y)和(y,x)中的一对。

lists = []
for x in range(3):
    for y in range(x + 1, 3):
        lists.append([x,y])

答案 2 :(得分:1)

如果您不想要那些“重复”,则需要 combination

  

组合是一种从集合中选择项目的方式,这样(与排列不同)选择的顺序无关紧要

>>> import itertools
>>> list(itertools.combinations(iterable=range(3), r=2))
[(0, 1), (0, 2), (1, 2)]

上面我使用了Python模块combinations()中的itertools

说明

  • 我设置了r=2,因为您希望子序列长度为2(您描述为[x, y]的形式)
  • iterable=range(3)参数只是用于组合的元素列表,因此range(3)会导致[0, 1, 2]
  • 应用于最终结果的list()只是强制将输出打印到控制台,否则itertools.combinations会返回一个迭代的迭代,逐个拉出元素。< / LI>

答案 3 :(得分:0)

易:

for x in range(3):
  for y in range(x, 3):
      lists.append([x,y])
相关问题