首页 > 解决方案 > 在python中生成一个长度为l的三进制数列表,可以逐位查询

问题描述

我想生成一个长度为 l 的三进制数列表并保存到字典中。然后我希望能够逐位比较这些数字并进行修改。

例如,如果长度为l=2,则字典应包含数字:00,01,02,10,11,12,20,21,22

然后我想做一些操作,比如将字典中条目的ith数字与条目的数字进行比较。像上面的列表一样,比较条目“20”的“0”和条目“21”的“1”jthkthlth

此外,我应该能够总结ith字典条目的数字。就像条目“11”的总和 = 2。

请建议我做上述事情的方法。我是 python 编码的新手。

这是我的尝试,但这并没有给我 2 位数字。所以关于如何从一个地方到十个地方等等的建议,将不胜感激:

dict = {}
n = 0
dict[0] = 00
while (n < 9):
   dict[n+1]= (dict[n] +1) % 3
   if dict[n+1] = 2
   n = n +1

print (dict)   `

标签: python

解决方案


itertools.product似乎给了你你想要的东西。它通常用于代替嵌套for循环,但有一个方便的repeatkwarg 可以让你的生活更轻松。

l = 3  # that's a lower-case L. Never use that in code, though, it looks like a 1.

digits = itertools.product(range(3), repeat=l)

# is equivalent to

def my_product():
    """the same as above itertools.product if l==3"""
    for i in range(3):
        for j in range(3):
            for k in range(3):
                yield (i, j, k)
my_digits = my_product()  # YUCK!

这会生成一个生成器(注意:不是列表!),它会生成您要查找的所有值 from (0, 0, 0)to (2, 2, 2)。要制作一个列表,只需将其转换为一个。

digits = list(itertools.product(range(3), repeat=l))  # still a lower-case L. Still don't do this.

然后比较数字,只需像任何 2D 列表一样使用索引。

first_value = digits[0]
first_digit = first_value[0]
assert first_digit == digits[0][0]

second_value = digits[1]
first_digit_of_second_value = second_value[0]
assert first_digit_of_second_value == digits[1][0]

if digits[0][0] == digits[1][0]:
    # that's these two:  v          v
    # digits ==         (0, 0, 0), (0, 0, 1), (0, 0, 2), ...
    do_whatever_you_want()

如果您想专门输出(0, 0, 0)000,您可以为此编写一个函数:

def sprint_tuple(tup):
    """Takes a tuple of digits and pretty Sprints them.

    >>> sprint_tuple((0, 0, 1))
    '001'
    """

    return ''.join([str(i) for i in tup])

然后遍历你digits并打印每个:

>>> for tup in digits:
...     print(sprint_tuple(tup))
000
001
002
010
...
222

推荐阅读