从变量列表创建布尔字典

2024-06-17 09:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用表达式的变量创建布尔字典。因此,如果表达式1有变量{x,y,z},我可以创建一个字典,在生成时返回类似{'x': True, 'y': True, 'z': True}, {'x': False, 'y': True, 'z': True} ... etc

但是我真的很挣扎,因为这个函数需要处理不同变量的集合/(也许我应该把它们放到列表中?),所以对于{x}来说,字典就是{'x' : True}, {'x' : False}

到目前为止,我正在尝试一个代码

def dicx(self):
    for i in self.vars():
        dicxow = { i : True for i in self.vars() }
        dicxow1 = dicxow.copy()
        dicxow1 = {i : False for i in self.vars() }
        return dicxow, dicxow1

其中self.vars()返回表达式中的所有变量

我不知道该从哪里着手,因为我不知道如何为每个不同的变量只更改字典的一部分,所以任何提示都将不胜感激。我的任务包括使用类,所以我使用类来完成这项任务(我不确定这是否会造成不同)

编辑:

好的,对不起,我只想为x个变量创建一个包含所有可能的真与假组合的字典,但我很难做到这一点。vars()从一个表达式返回一组变量,例如{x,y},我想从中创建一个函数来生成x和y的每个True和False组合


Tags: 函数代码inselffalsetrue列表for
1条回答
网友
1楼 · 发布于 2024-06-17 09:15:54

我想这和你想要的差不多。要获得n变量的TrueFalse的所有组合,它只生成从0到2的所有整数值n-1。我把所有东西都放在一个虚拟的class中,使它更像你的作业

from pprint import pprint

class Expression:

    def __init__(self, *variables):
        self.variables = variables

    def vars(self):
        return self.variables

    def dicx(self):
        def bools(bit_string):  # Helper function
            """ Convert string of binary chars to list of corresponding booleans. """
            return [ch == '1' for ch in bit_string]

        n = len(self.vars())
        vals = list(range(2**n))
        bits = [format(v, f'0{n}b') for v in vals]
        return [dict(zip(self.vars(), bools(combo))) for combo in bits]


instance = Expression('x', 'y', 'z')
pprint(instance.dicx(), sort_dicts=False)

输出:

[{'x': False, 'y': False, 'z': False},
 {'x': False, 'y': False, 'z': True},
 {'x': False, 'y': True, 'z': False},
 {'x': False, 'y': True, 'z': True},
 {'x': True, 'y': False, 'z': False},
 {'x': True, 'y': False, 'z': True},
 {'x': True, 'y': True, 'z': False},
 {'x': True, 'y': True, 'z': True}]

相关问题 更多 >