简体   繁体   English

创建二进制字符串列表(Python)

[英]create list of binary strings (Python)

I have a directed Multigraph and would like to identify the nodes with a binary string representing the coordinates of each node. 我有一个定向Multigraph,想用代表每个节点坐标的二进制字符串标识节点。
How can I build a list of these coordinates depending on the dimension of the multigraph? 如何根据多图的尺寸构建这些坐标的列表?

Also the order of the coordinates is relevant. 坐标的顺序也是相关的。 The first number is zero, then all numbers with one 1 in them, then all numbers with two 1s in them and so on. 第一个数字为零,然后所有数字中都有一个1,然后所有数字中都有两个1,依此类推。 All these groupings of numbers have to be in reversed lexicographic order. 所有这些数字分组必须按相反的字典顺序排列。

An example: 一个例子:

n = 3
bin_str = [000, 100, 010, 001, 110 101, 011, 111]

Is there a clever way to do this? 有聪明的方法吗?

You could use itertools.product : 您可以使用itertools.product

from itertools import product
n = 3
# generate product in reverse lexicographic order
bin_str = [''.join(p) for p in product('10', repeat=n)]
# ['111', '110', '101', '100', '011', '010', '001', '000']    
# sort by number of ones
bin_str.sort(key=lambda s: s.count('1'))
# ['000', '100', '010', '001', '110', '101', '011', '111']

can also be done using recursion 也可以使用递归来完成

def bin_list(n):
      if n == 0:
            #base case
            return ['']
      else:
            return [i + '0' for i in bin_list(n-1)] + [i + '1' for i in bin_list(n-1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM