在python中生成两项的所有可能长度为n的组合

编程入门 行业动态 更新时间:2024-10-13 16:18:35
本文介绍了在python中生成两项的所有可能长度为n的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试从两个可能的项目生成长度为n的列表。例如一个示例可能是长度为4的列表,包括零或一个将为0000、0001、0010、0100、1000、1001等。预先感谢, Jack

I am trying to generate a list of length n from two possible items. e.g. One example could be, a list of length 4 comprising zeros or ones which would be 0000, 0001, 0010, 0100, 1000, 1001, etc. Thanks in advance, Jack

推荐答案

使用 itertools.product :

In [1]: from itertools import product In [2]: list(product((0, 1), repeat=4)) Out[2]: [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]

以整数字符串形式打印int:

You can also just print ints as binary strings:

In [3]: for i in range(2**4): ...: print('{:04b}'.format(i)) ...: 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111

更多推荐

在python中生成两项的所有可能长度为n的组合

本文发布于:2023-11-29 14:15:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646625.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   两项   长度为   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!