Python:打印4个变量的排列

Python: Print permutations of 4 variables

我发现这个 Python 脚本可以打印给定变量的所有排列。我是一个完整的 Python 新手,但经过一些修改后,它几乎完全符合我的需要。

这是我目前得到的:

blocks =  [ "0", "1a", "2a", "2b" ] # variables
num_blocks = len( blocks )
num_places = 4  # number of places

for i in range( pow( len( blocks ), num_places ) ): 
    value = i
    indexes = []

    while value:    
        indexes.append( value % num_blocks )
        value = value // num_blocks

    # print( i + 1 ) # alternatively print number of each permutation

    for j in range( len( indexes ), num_places ):
        print blocks[ num_blocks - 1 ]

    for j in range( len( indexes ) - 1, -1, -1 ):
        print( blocks[ num_blocks - 1 - indexes[ j ] ] )

    print " "  # add a line break after each entry

输出为

2b
2b
2b
2b

2b
2b
2b
2a

等等

我怎样才能 A) 将输出更改为

2b2b2b2b
2b2b2b2a

等等

and B) 仅打印包含最后一个变量的事件,在本例中为“2b”。 出于本示例的目的,我仅包含四个变量:0、1a、2a、2b。该脚本打印这四个变量的所有可能组合,从 0000 到 2b2b2b2b 以及介于两者之间的任何值。是否可以只打印包含最后一个变量 2b 的组合?那么例如 2b2a1a0 或 1a1a02b,而不是 2a2a1a0 或 2a01a1a?稍后,将包含更多变量(3a、3b 等),但脚本应仅列出包括最后一个变量的排列。

提前致谢!

乔治

已编辑以澄清第二个问题。

更新:这将澄清您的两个问题。谢谢

blocks =  [ "0", "1a", "2a", "2b" ] # variables
num_blocks = len( blocks )
num_places = 4  # number of places

for i in range( pow( len( blocks ), num_places ) ): 
  value = i
  indexes = []

  while value:    
      indexes.append(value % num_blocks)
      value = value // num_blocks

  # print( i + 1 ) # alternatively print number of each permutation
  
  output = ''
  for j in range( len( indexes ), num_places ):
      output +=  str(blocks[ num_blocks - 1 ])
  
  for j in range( len( indexes ) - 1, -1, -1 ):
      output += str(blocks[ num_blocks - 1 - indexes[j] ])
  
  search = blocks[3] # search '2b' in output
  if output.find(search) != -1 :
      print output,
      print " "