开发者

convert a mixed list of strings to a list of integer

I not familiar with python and need help t开发者_如何学JAVAo convert a list containing strings and numbers (all represented as strings!) to a new list that include only the numbers.

  • input string : ['LOAD','0x00134','0','0','R','E','0x1df0','0x1df0']
  • result needed: [0x00134,0,0,0x1df0,0x1df0]

All non-numeric entries like 'LOAD' and 'R', 'E' should be removed.


input = ['LOAD','0x00134','0','0','R','E','0x1df0','0x1df0']

def tryInt(x):
    base = 10
    if x.startswith('0x'): base = 16
    try: return int(x, base)
    except ValueError: return None

filter(lambda x: x is not None, map(tryInt, input))


You can use this function from: http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Python

def is_numeric(lit):
    'Return value of numeric literal string or ValueError exception'

    # Handle '0'
    if lit == '0': return 0
    # Hex/Binary
    litneg = lit[1:] if lit[0] == '-' else lit
    if litneg[0] == '0':
        if litneg[1] in 'xX':
            return int(lit,16)
        elif litneg[1] in 'bB':
            return int(lit,2)
        else:
            try:
                return int(lit,8)
            except ValueError:
                pass

    # Int/Float/Complex
    try:
        return int(lit)
    except ValueError:
        pass
    try:
        return float(lit)
    except ValueError:
        pass
    return complex(lit)

This way:

def main():
    values = ['LOAD', '0x00134', '0', '0', 'R', 'E', '0x1df0', '0x1df0']
    numbers = []
    for value in values:
        try:
            number = is_numeric(value)
        except ValueError:
            continue
        numbers.append(number)


May be an overkill, but a very flexible solution. You may want to support octal or Roman numbers later ;-)

import re

parsing_functions = [
    (r'^(\d+)$', int),
    (r'^0x([\dA-F]+)$(?i)', lambda x:int(x,16))
]
parsing_functions = [(re.compile(x),y) for x,y in parsing_functions]

def parse_integers(input) :
    result = []
    for x in input :
        for regex, parsing_function in parsing_functions :
            match = regex.match(x)
            if match :
                result.append(parsing_function(match.group(1)))
    return result

input = ['LOAD','0x00134','0','0','R','E','0x1df0','0x1df0']
print parse_integers(input)


def list2num(mylist):
    result = []
    for item in mylist:
        try:
            if item.lower().startswith("0x"):
                result.append(int(item, 16))
            else:
                result.append(int(item))
        except ValueError:
            pass
    return result

This gives you

>>> numbers = ['LOAD','0x00134','0','0','R','E','0x1df0','0x1df0']
>>> list2num(numbers)
[308, 0, 0, 7664, 7664]

Or better, if you just need an iterator, we don't have to build that result list in memory:

def list2num(mylist):
    for item in mylist:
        try:
            if item.lower().startswith("0x"):
                yield int(item, 16)
            else:
                yield int(item)
        except ValueError:
            pass
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜