Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我很难理解Python中的这段代码_Python_Permutation - Fatal编程技术网

我很难理解Python中的这段代码

我很难理解Python中的这段代码,python,permutation,Python,Permutation,下面是实际工作的代码。它返回任意长度的给定字符串的所有可能排列 例如:置换('ab')返回['ab','ba] def permutations(string): if len(string) == 1: return set(string) first = string[0] rest = permutations(string[1:]) #This is the line that i do not understand result = set() for i in

下面是实际工作的代码。它返回任意长度的给定字符串的所有可能排列 例如:
置换('ab')返回['ab','ba]

def permutations(string):
  if len(string) == 1: return set(string)
  first = string[0]
  rest = permutations(string[1:])  #This is the line that i do not understand
  result = set()
  for i in range(0, len(string)):
    for p in rest:
      result.add(p[0:i] + first + p[i:])
  return result
我不知道这一行(上面的注释)
rest=permutations(string[1:])
在做什么。 我试着这样写它,但是这样写时它不能正常工作

这两行代码之间的区别是什么

rest = permutations(string[1:]) 

它似乎在函数内部调用自己,但我不确定这会有什么不同。

它在做一个,编程中的一个流行概念。在每次迭代中,它都使用一个新字符串作为参数调用同一个函数,该参数是在“string[1:]”之后获得的


希望这有帮助。

这是一个对切片字符串递归调用置换函数。字符串[1:]表示字符串的切片[start:end]。这是很好的切片阅读材料是的,这很有意义。我很感谢你的回复,这帮了我很大的忙!
rest = string[1:]