【问题标题】:how to pair values from python list [closed]如何配对python列表中的值[关闭]
【发布时间】:2013-11-29 10:43:59
【问题描述】:
list = [1,2,3,4]

我想得到下面的结果并将它们存储在 csv 文件中。 (共 6 行)

1,2
1,3
1,4
2,3
2,4
3,4

这有什么功能,或者我怎样才能完成并将其存储在 csv 文件中?

【问题讨论】:

    标签: python list function


    【解决方案1】:

    itertools是你的朋友...

    http://docs.python.org/2/library/itertools.html

    >>> import itertools
    >>> x = [1, 2, 3, 4]
    >>> list(itertools.combinations(x, 2))
    [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
    

    【讨论】:

    • OP:使用'\n'.join(','.join(map(str, v)) for v in itertools.combinations(x, 2)) 获得所需的输出。
    【解决方案2】:

    使用itertools.combinations。它内置在 Python 2.6+ 中。

    import itertools
    
    pairs = itertools.combinations(list, 2)
    

    【讨论】:

      【解决方案3】:

      一种选择是使用itertools.permutations 和列表理解:

      >>> [(x, y) for x, y in itertools.permutations(mylist, 2) if x < y]
      [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
      

      条件x &lt; y 确保您只获得x 低于y 的排列。

      更好的选择是使用itertools.combinations(mylist, 2)

      【讨论】:

      • 当 itertools.combinations 产生想要的结果时,何必费心呢?
      • 那为什么不用combinations呢?
      • 是的,这实际上更好。
      • 如果你要反高尔夫,你可以先用product 建立combinations,然后再用combinations 建立permutations。 :)
      【解决方案4】:

      这很简单,你可以自己做:

      l=[1,2,3,4]
      for i in range(0,len(l)):
          for j in range (i+1,len(l)):
              print l[i],l[j]
      

      但是使用itertools 的解决方案可以更容易泛化。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 2022-11-06
        • 2023-04-11
        • 2017-01-26
        • 2023-03-18
        • 1970-01-01
        相关资源
        最近更新 更多