【问题标题】:Nested For Loops Using List Comprehension使用列表理解嵌套 For 循环
【发布时间】:2011-04-07 16:23:42
【问题描述】:

如果我有两个字符串,'abc''def',我可以使用两个 for 循环获得它们的所有组合:

for j in s1:
  for k in s2:
    print(j, k)

但是,我希望能够使用列表理解来做到这一点。我尝试了很多方法,但从未设法得到它。有谁知道怎么做?

【问题讨论】:

    标签: python for-loop list-comprehension


    【解决方案1】:
    lst = [j + k for j in s1 for k in s2]
    

    lst = [(j, k) for j in s1 for k in s2]
    

    如果你想要元组。

    就像问题一样,for j... 是外循环,for k... 是内循环。

    基本上,您可以在列表理解中拥有任意数量的独立“for x in y”子句,只需一个接一个地粘贴即可。

    为了使其更具可读性,请使用多行:

    lst = [
           j + k         # result
           for j in s1   # for loop 
             for k in s2 # for loop
                         # condition   
           ]
    

    【讨论】:

    • 如果你想用嵌套循环遍历一个嵌套列表怎么办?类似于: [print('a') for ax in axs for axs in axes] 在 [None, None...] 上打印一堆直到 len(axes)
    • @Pablo 我认为你的循环颠倒了。 L1 = [[[e1, e2, ...], ...], ...] -> [ e for L2 in L1 for L3 in L2 for e in L3 ]
    • for 语句的顺序与您将其编写为两个单独的行上的两个 for 循环一样。
    • aaronasterling 我可以在下面使用条件语句吗?
    • lst = [j+k if BLAHBLAHBLAH for j in s1 for k in s2] 什么的
    【解决方案2】:

    由于这本质上是一个笛卡尔积,您也可以使用itertools.product。我认为它更清晰,尤其是当您有更多输入迭代时。

    itertools.product('abc', 'def', 'ghi')
    

    【讨论】:

      【解决方案3】:

      也试试递归:

      s=""
      s1="abc"
      s2="def"
      def combinations(s,l):
          if l==0:
              print s
          else:
              combinations(s+s1[len(s1)-l],l-1)
              combinations(s+s2[len(s2)-l],l-1)
      
      combinations(s,len(s1))
      

      为您提供 8 种组合:

      abc
      abf
      aec
      aef
      dbc
      dbf
      dec
      def
      

      【讨论】:

      • 根据OP的问题,我认为输出应该给出几个字母,应该有9个组合。
      • 发生了什么:abd, abe, acd, ace, acf, adb, adc, ade, adf, aeb, aed, afb, afc, afd, afe,以及所有以 c 开头的, e,还是 f?即使顺序不重要,省略的还有:bda、ade 等。
      • 这个方法是,最左边的位置只能是“a”或“d”,中间位置只能是“b”或“e”,最右边的位置只能是是“c”或“f”。
      猜你喜欢
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多