Python programming USES * unpacking and itertools.product of cartesian product method

  • 2020-06-15 09:45:53
  • OfStack

This article illustrates Python programming using * to unpack and itertools.product() The cartesian product. To share for your reference, specific as follows:

[question]

There is currently a 1 string s = "['a', 'b'],['c', 'd']" , want to break it down into two lists:


list1 = ['a', 'b']
list2 = ['c', 'd']

After using itertools.product() The Cartesian product should be written as:


for i in itertools.product(list1, list2):
  print i

The result is:


('a', 'c')
('a', 'd')
('b', 'c')
('b', 'd')

However, using eval(s) you get 1 tuple. If the argument to product is a tuple, 1 will definitely report an error (the argument to product is two lists, with a variable number of elements in each list). How to break?

"Answer"

It's only one * away. * is an assignment technique in python called unpacking. I'm sure many of you have def func(*args, **kwargs) In this way, * represents an indefinite number of arguments passed in as tuple and ** as dict. A similar method can be used when using functions. When calling the func(*args) function, it is equivalent to taking args, a tuple, apart and passing it into the function as a parameter. Just be careful that the number and type of elements in args must correspond to the function definition 1, otherwise an SyntaxError: invalid syntax syntax error will be reported.

For example, in this case, it could be written as:


for i in itertools.product(*eval(s)):
  print i

And then you get the result.

Three tips for this question:

(1) itertools.product() Take the Cartesian product. itertools this module has quite a lot of awesome mathematical algorithms, such as full permutation function permutations, combined function combinations and so on, sometimes want a mathematical function but do not want to write their own, you can find here, there may be a surprise.

(2) eval() String evaluation. eval and exec, the two inverse functions in python, are powerful enough to make people worry about their security.

(3) * Unpack. As explained above, you can only use it in a limited number of situations. You can only use it when you have no way out. Don't count on it to benefit your program too much.

For more information about Python, please refer to Python Data Structure and Algorithm Tutorial, Python Encryption and Decryption Algorithm and Skills Summary, Python Coding skills Summary, Python Function Use Skills Summary, Python String Manipulation Skills Summary and Python Introduction and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: