Python:遍历字符串,检查元素并输入字典键值对

0 投票
2 回答
1312 浏览
提问于 2025-04-15 14:21

我有一个函数,它会根据给定的参数返回一个8位长的二进制字符串。

def rule(x):
rule = bin(x)[2:].zfill(8)
return rule

我想要遍历这个字符串的每一个位置,检查它是0还是1。我试着写了这样的代码:

def rule(x):
   rule = bin(x)[2:].zfill(8)
   while i < len(rule(x)):
         if rule[i] == '0'
            ruleList = {i:'OFF'}
         elif rule[i] == '1'
           ruleList = {i:'ON'}
         i = i + 1
    return ruleList

但是这段代码不管用。我收到了“错误:对象不可下标”的提示。我想做的是写一个函数,输入像这样的内容:

Input: 30
1. Converts to '00011110' (So far, so good)..
2. Checks if rule(30)[i] is '0' or '1' ('0' in this case where i = 0) 
3. Then puts the result in a key value pair, where the index of the
string is the key and the state (on
or off) is the value. 
4. The end result would be 'ruleList', where print ruleList
would yield something like this:
{0:'Off',1:'Off',2:'Off',3:'On',4:'On',5:'On',6:'On',7:'Off'}

有人能帮我吗?我刚开始学Python和编程,所以这个函数对我来说有点难。我希望能看到一些更有经验的程序员对这个问题的解决方案。

谢谢,

2 个回答

2

这就是你想要的吗?

def rule(x) :
    rule = bin(x)[2:].zfill(8)
    return dict((index, 'ON' if int(i) else 'OFF') for index, i in enumerate(rule)) 
0

这是你写的代码一个更符合Python风格的版本——希望注释能让你理解代码的意思。

def rule(x):
    rule = bin(x)[2:].zfill(8)
    ruleDict = {} # create an empty dictionary
    for i,c in enumerate(rule): # i = index, c = character at index, for each character in rule
        # Leftmost bit of rule is key 0, increasing as you move right
        ruleDict[i] = 'OFF' if c == '0' else 'ON' 
        # could have been written as:
        # if c == '0':
        #    ruleDict[i] = 'OFF'
        # else:
        #    ruleDict[i] = 'ON'

        # To make it so ruleDict[0] is the LSB of the number:
        #ruleDict[len(rule)-1-i] = 'OFF' if c == '0' else 'ON' 
    return ruleDict

print rule(30)

输出结果:

$ python rule.py
{0: 'OFF', 1: 'ON', 2: 'ON', 3: 'ON', 4: 'ON', 5: 'OFF', 6: 'OFF', 7: 'OFF'}

输出结果实际上是反着打印的,因为字典的键没有保证会按照特定的顺序打印。不过,你会注意到这些数字是对应的,最大的数字是最重要的位。这就是为什么我们要用 len(rule)-1-i 这种方式来索引 ruleDict

撰写回答