简体   繁体   English

如何增加 function 中的循环数?

[英]How to increase number of loops in a function?

I have a code here我这里有代码

letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ret = ""
for i in range(26):
  for j in letters:
    ret += f"({letters[i]},{j})"
print(ret)

#Output: 
(a,a)(a,b)(a,c)(a,d)(a,e)(a,f)(a,g)(a,h)(a,i)(a,j)(a,k)(a,l)(a,m)(a,n)(a,o)(a,p)...(z,y)(z,z)

The problem I am trying to figure out is:我想弄清楚的问题是:

When I am trying to increase the number of permutations, for example from 2 digits to 3 digits, I have to add another loop.当我试图增加排列的数量时,例如从 2 位到 3 位,我必须添加另一个循环。 How do I increase the number of loops as I increase the number of digits, when I want to implement this as a function, can anyone help:(当我想将其实现为 function 时,如何在增加位数时增加循环数,任何人都可以帮忙:(


This is what i did when i tried to increase the number of digits from 2 to 3:这是我尝试将位数从 2 增加到 3 时所做的:

for i in range(26):
  for k in range(26):
    for j in letters:
      ret += "(" + str(letters[i]) + "," + str(letters[k]) + "," + j + ")"
print(ret)

#Output
(a,a,a)(a,a,b)(a,a,c)(a,a,d)(a,a,e)(a,a,f)(a,a,g)(a,a,h)(a,a,i)(a,a,j)(a,a,k)(a,a,l)(a,a,m)...(z,z,z)

How do i implement this in a function?我如何在 function 中实现这一点?

You can achieve this using the itertools like this您可以像这样使用 itertools 来实现这一点

import itertools

def perm_func(arr, x):
    ret_str = ""
    p for p in itertools.product(arr, repeat=x):
        ret_str += str(p)

    return ret_str

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

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