簡體   English   中英

Python:遍歷字符串,檢查其元素並輸入字典鍵值對

[英]Python: Traversing a string, checking its element, and inputting dictionary key-value pairs

我有一個函數,該函數返回給定參數的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和程序設計的新手,因此已證明此功能頗具挑戰性。 我希望看到一些針對此特定問題的更有經驗的編碼器解決方案。

謝謝,

這是你想要的嗎?

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

這是您編寫的代碼的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'}

輸出實際上恰好以相反的順序打印,因為無法保證字典的鍵將以任何特定的順序打印。 但是,您會注意到,數字相對應,其中最大的數字是最高有效位。 這就是為什么我們不得不在len(rule)-1-i上做ruleDict的有趣工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM