社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python中用逐位查询法生成长度为l的三元数列表

user2764635 • 6 年前 • 375 次点击  

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

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

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

我也应该能把 伊斯 词典的条目。就像条目“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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40351
文章 [ 1 ]  |  最新文章 6 年前
Adam Smith
Reply   •   1 楼
Adam Smith    6 年前

itertools.product 似乎给了你想要的东西。它经常用来代替嵌套 for 循环,但有一个方便的 repeat 这让你在这里的生活更轻松。

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!

这会产生 发电机 (注意:不是列表!)它产生了你想要的所有价值观 (0, 0, 0) (2, 2, 2) . 要列出一个列表,只需将其转换为一个。

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

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

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