将混合的字符串列表转换为整数列表

时间:2011-09-01 05:47:02

标签: python string list integer

我不熟悉python,需要帮助将包含字符串和数字的列表(全部表示为字符串!)转换为仅包含数字的新列表。

  • 输入字符串:['LOAD','0x00134','0','0','R','E','0x1df0','0x1df0']
  • 需要的结果:[0x00134,0,0,0x1df0,0x1df0]

应删除所有非数字条目,如“LOAD”和“R”,“E”。

4 个答案:

答案 0 :(得分:2)

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))

答案 1 :(得分:1)

可能是一种矫枉过正,但却是一种非常灵活的解决方案。您可能希望稍后支持八进制或罗马数字; - )

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)

答案 2 :(得分:0)

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

这会给你

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

或者更好的是,如果你只需要一个迭代器,我们就不必在内存中构建那个结果列表:

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

答案 3 :(得分:0)

您可以使用以下功能: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)

这样:

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)