从列表中的元组中删除空字符串

use*_*319 0 python regex tuples list

现在我有三个从RE findall函数生成的列表,我试图从列表中的元组中删除一些空字符串.并且数字也应该在过程中转换为整数:

拿到:[('', '', '1', '1')]

预期: [(1, 1)]

拿到: [('', '', '20', '500'), ('21', 'failed', '', '')]

预期: [(20, 500), (21, 'failed')]

拿到: [('3', 'failed', '', ''), ('', '', '48', '23'), ('', '', '96', '0')]

预期: [(3, 'failed'), (48, 23), (96, 0)]

有任何想法吗?

ayc*_*dee 5

这个怎么样:

def sanitize(t):                                
    for i in t:
        try:
            yield int(i)
        except ValueError:
            yield i

inputs = [('3', 'failed', '', ''), ('', '', '48', '23'), ('', '', '96', '0')]
map(tuple, map(sanitize, [filter(None, i) for i in inputs]))
Run Code Online (Sandbox Code Playgroud)

给出输出:

[(3, 'failed'), (48, 23), (96, 0)]
Run Code Online (Sandbox Code Playgroud)

filter是一个对序列进行操作并仅返回“真实”元素的函数。空字符串是假的。Map 是另一个函数,它接受一个序列并通过给定的函数运行该序列中的每个元素。在这种情况下,该函数sanitize将字符串转换为 int(如果可以),否则仅返回字符串。

我们使用yield而不是returnsanitize函数中作为将另一个序列返回到下一个映射函数的简单方法。或者,我们可以在函数内构建一个列表并返回它。


jay*_*elm 5

使用元组构造函数的嵌套列表理解:

>>> lst = [('', '', '20', '500'), ('21', 'failed', '', '')]
>>> [(tuple(int(x) if x.isdigit() else x for x in _ if x)) for _ in lst]
[(20, 500), (21, 'failed')]
Run Code Online (Sandbox Code Playgroud)

对于每个元组(_)lst,tuple使用生成器表达式构造一个.单独的元组构造函数如下:

tuple(int(x) if x.isdigit() else x for x in _ if x)
Run Code Online (Sandbox Code Playgroud)

这似乎令人困惑,但我会打破它.对于x元组中的每个字符串_(这是一个元组lst),构造一个元组.if x检查字符串是否为空.(如果string x为空,x则为false.)if x,生成器表达式将产生x或者int(x)取决于是否x是字符串形式的数字.(尝试将非数字字符串转换为整数将导致异常.)

对于每个元组_lst,发生器创建一个新的,相同的元组,除了空,假字符串被过滤掉并且任何数字串被转换成int

以上代码相当于:

new_lst = []

for _ in lst: # For each tuple in lst
    for x in _: # For each string in tuple
        temp_tuple = ()
        if x: # Only add to tuple if string is not empty
            if x.isdigit(): # If x is a digit in string form
                temp_tuple += (int(x),) # Convert to int
            else:
                temp_tuple += (x,) # Keep string
    new_lst.append(temp_tuple)
Run Code Online (Sandbox Code Playgroud)