Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Python get Cartesian products from a list

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how Python gets the Cartesian product from the list. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. You can use itertools.product in the standard library to get Cartesian product.

From itertools import product somelists = [[1,2,3], ['await,' b'], [4,5]] result = list (product (* somelists)) print (result)

2. Iterative method.

Def cartesian_iterative (pools): result = [[]] for pool in pools: result = [x + [y] for x in result for y in pool] return result

3. Recursive method.

Def cartesian_recursive (pools): if len (pools) > 2: pools [0] = product (pools [0], pools [1]) del pools [1] return cartesian_recursive (pools) else: pools [0] = product (pools [0], pools [1]) del pools [1] return poolsdef product (x, y): return [xx + [yy] if isinstance (xx, list) else [xx] + [yy] for xx in x for yy in y]

4. Lambda method.

Def cartesian_reduct (pools): return reduce (lambda XMagery y: product (XMagne y), pools) Thank you for reading! This is the end of the article on "how Python gets Cartesian products from the list". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report