简体   繁体   English

Python:基于模式创建动态循环

[英]Python: Create dynamic loop based on pattern

I'm still learning to code in Python 我仍在学习用Python编写代码

I want to generate a string based on pattern, the only way I know is by using for loop. 我想基于模式生成一个字符串,我知道的唯一方法是使用for循环。

In example code below, I create a loop for "vcvcv" pattern. 在下面的示例代码中,我为“ vcvcv”模式创建了一个循环。 c=consonant, v=vowel c =辅音,v =元音

How to create a dynamic loop, based on pattern that I provide to the script? 如何基于我提供给脚本的模式创建动态循环?

eg. 例如。 if pattern is "cvcvc" the loop should be build to produce the string 如果模式为“ cvcvc”,则应构建循环以生成字符串

Help appeciated. 帮助表示赞赏。

Thanks. 谢谢。

#!/bin/env python

vowel="aeiou"
consonant="bcdfghjklmnpqrstvwxyz"

lvowel=list(vowel)
lconsonant=list(consonant)

# pattern for "vcvcv" = ababa
for a in lvowel:
  for b in lconsonant:
    for c in lvowel:
      for d in lconsonant:
            for e in lvowel:
                  myname=a+b+c+d+e
                  print myname

# pattern for "cvcvc" = babab
# how to make the loop dynamic based on pattern ?

Something like this should work: 这样的事情应该起作用:

import itertools

mapping = {
    'v': 'aeiou',
    'c': 'bcdfghjklmnpqrstvwxyz'
}

pattern = 'vcvcv'

for thing in itertools.product(*map(mapping.get, pattern)):
    print ''.join(thing)

Here's roughly how it works: 大致运作方式如下:

  • map(mapping.get, pattern) just converts 'vcv' to ['aeiou', 'bcdfghjklmnpqrstvwxyz', 'aeiou'] . map(mapping.get, pattern)只是将'vcv'转换为['aeiou', 'bcdfghjklmnpqrstvwxyz', 'aeiou'] It replaces each letter with the corresponding list of characters. 它将每个字母替换为相应的字符列表。
  • *map(...) unpacks the argument list. *map(...)解压缩参数列表。
  • itertools.product() is like a bunch of nested for loops. itertools.product()就像一堆嵌套的for循环。
  • ''.join(thing) joins the list of characters into a single string. ''.join(thing)将字符列表合并为一个字符串。

If you want to do this without itertools , you'll have to make a recursive function. 如果要在没有itertools情况下执行此操作,则必须创建一个递归函数。

If you're just getting into programming and want to see a more general solution than the itertools one listed above, then recursion is your best bet, allowing you to arbitrarily nest loops. 如果您只是想编程,并且希望看到比上面列出的itertools更通用的解决方案,那么递归是最好的选择,允许您随意嵌套循环。

There is a slight complication here, which you could use Python generators for, or else use simpler (but messier) constructs. 这里有一点复杂,您可以使用Python生成器 ,也可以使用更简单(但更混乱)的构造。 An example of the latter is shown below. 后者的示例如下所示。

Something like 就像是

def continuePattern(pat, strSoFar):
  if pat == '':
    print strSoFar
  elif pat[0] == 'v':
    for c in lvowel:
       continuePattern(pat[1:], strSoFar + c)
  elif pat[0] == 'c':
    for c in lconsonant:
       continuePattern(pat[1:], strSoFar + c)

This is one of several possible implementations, and one of the two most naive ones I can imagine. 这是几种可能的实现之一,也是我能想到的两个最幼稚的实现之一。

A somewhat more elaborate but easily customizable version for the first n permutations is given below, 下面给出了前n个排列的更为精细但易于定制的版本,

def gen_pattern( seq, op = "" ):
      vowel="aeiou"
      consonant="bcdfghjklmnpqrstvwxyz"

      lvowel=list(vowel)
      lconsonant=list(consonant)
      if ( not seq ):
            print op
            return

      if ( seq[0] == 'v' ):
            for v in lvowel:
                  gen_pattern( seq[1:], op+v )
      elif ( seq[0] == 'c' ):
            for c in lconsonant:
                  gen_pattern( seq[1:],op+c )

if __name__ == "__main__":
      gen_pattern("vcvcv")

I agree it is more work though! 我同意这是更多工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM