为了账号安全,请及时绑定邮箱和手机立即绑定

Python:打印 4 个变量的排列

Python:打印 4 个变量的排列

小怪兽爱吃肉 2021-09-02 19:18:27
我发现这个 Python 脚本可以打印给定变量的所有排列。我是一个完整的 Python 新手,但经过一些修改后,它几乎完全符合我的需要。这是我到目前为止所得到的:blocks =  [ "0", "1a", "2a", "2b" ] # variablesnum_blocks = len( blocks )num_places = 4  # number of placesfor 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输出是2b2b2b2b2b2b2b2a等等。IA) 如何将输出更改为2b2b2b2b2b2b2b2a等等。和 B) 只打印包含最后一个变量的出现,在这种情况下是“2b”。出于本示例的目的,我仅包含四个变量:0、1a、2a、2b。该脚本打印这四个变量的所有可能组合,从 0000 到 2b2b2b2b 以及介于两者之间的任何组合。是否可以仅打印包含最后一个变量 2b 的组合?因此,例如 2b2a1a0 或 1a1a02b,但不是 2a2a1a0 或 2a01a1a?稍后,将包含更多变量(3a、3b 等),但脚本应仅列出包括最后一个变量的排列。提前致谢!乔治编辑以澄清第二个问题。
查看完整描述

1 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

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


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


查看完整回答
反对 回复 2021-09-02
  • 1 回答
  • 0 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信