我有一个函数返回给定参数的8位长二进制字符串:
def rule(x):
rule = bin(x)[2:].zfill(8)
return rule
我想遍历此字符串的每个索引并检查它是零还是一个。我试着编写这样的代码:
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和编程的新手,所以这个函数已被证明是非常具有挑战性的。我希望看到一些更有经验的编码器解决这个特殊问题。
谢谢,
答案 0 :(得分: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))
答案 1 :(得分:0)
这是你编写的代码的更多Pythonic版本 - 希望这些注释能够很好地解释代码。
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'}
输出实际发生以相反的顺序打印,因为无法保证字典的键将以任何特定顺序打印。但是,您会注意到数字对应的最大数字是最重要的位。这就是为什么我们必须在ruleDict
进行索引len(rule)-1-i
的有趣业务。