Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use python to output all permutations of list elements

Shulou Source: shulou.com Published: 2022-06-02 18:26:44 09月11日 Update

This article introduces the knowledge of "how to use python to output all the arrangement forms of list elements". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

['axiao,' baked,'c'] output ['await,' baked,'c'] ['baked,' baked,'b'] ['baked,' clocked,'a'] ['cased,' clocked,'b'] ['cased,' baked,'a']

Method 1: use recursive method to realize

Def permutation (li): len_list = len (li) if len_list = = 1: return li result = [] for i in range (len_list): res_list = li [: I] + li [iTun1:] s = li [I] per_result = permutation (res_list) if len (per_result) = 1: result.append (Li [I: iTun1] + per_result) else: result + = [[s] + j for j in per_result] return result

Method 2: use the module that comes with python

Import itertools def permutation (li): print (list (itertools.permutations (li)

Supplementary expansion: python realizes the full arrangement of four numbers

First of all, we use the general practice to complete the loop exchange.

Lst = [1,3,5,8] for i in range (0, len (lst)): lst [I], lst [0] = lst [0], lst [I] for j in range (1, len (lst)): lst [j], lst [1] = lst [1], lst [j] for h in range (2, len (lst)): print (lst) lst [j], lst [1] = lst [1], lst [j] lst [I] Lst [0] = lst [0], lst [I]

If the list is longer and there are more elements, the above general methods will be more difficult to implement, so let's implement them recursively.

Def permutations (position): if position = = len (lst)-1: print (lst) else: for index in range (position, len (lst)): lst [index], lst [position] = lst [position], lst [index] permutations (position+1) lst [index], lst [position] = lst [position], LST [index] permutations (0) "how to use python to output all permutations of list elements" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Output element method form content general way more knowledge recursion laborious practical successful learning next practice dilemma reality situation number article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS vpn NVidia Shulou Information Shulou Tech Info