如何用'0'替换子列表中的空字符串?

时间:2014-02-17 07:16:36

标签: python list

我有一个子列表列表,每个子列表中的项目有时都是空白的。我想用'0'替换所有空白项目。

Original_List = [['Thomas Jefferson', '0.0', '0', '0', '6.0', '0', '12', '177', '0', '', '0', '', '', '', '24000.0', '', '', '0'], ['George Washington', '0.0', '0', '0', '0.0', '0', '0', '214', '6', '', '0', '', '', '', '', '', '', '0'], ['Barack Obama', '2.0', '0', '0', '2.0', '0', '0', '525', '3', '', '0', '', '', '', '24000.0', '20000.0', '94000.0', '114000.0']]


Desired_List = [['Thomas Jefferson', '0.0', '0', '0', '6.0', '0', '12', '177', '0', '0', '0', '0', '0', '0', '24000.0', '0', '0', '0'], ['George Washington', '0.0', '0', '0', '0.0', '0', '0', '214', '6', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['Barack Obama', '2.0', '0', '0', '2.0', '0', '0', '525', '3', '0', '0', '0', '0', '0', '24000.0', '20000.0', '94000.0', '114000.0']]

我试过了:

  return [map(lambda List_Item: re.sub('','0',List_Item),subli) for subli in lst]

这最终会用零替换错误的项目。

1 个答案:

答案 0 :(得分:3)

空字符串是虚假值。

使用or运算符,您可以获得'0'空字符串:

>>> '' or '0'
'0'
>>> '123' or '0'
'123'

>>> Original_List = [
    ['Thomas Jefferson', '0.0', '0', '0', '6.0', '0', '12', '177', '0', '', '0', '', '', '', '24000.0', '', '', '0'],
    ['George Washington', '0.0', '0', '0', '0.0', '0', '0', '214', '6', '', '0', '', '', '', '', '', '', '0'],
    ['Barack Obama', '2.0', '0', '0', '2.0', '0', '0', '525', '3', '', '0', '', '', '', '24000.0', '20000.0', '94000.0', '114000.0']
]
>>> [[x or '0' for x in xs] for xs in Original_List]
[['Thomas Jefferson', '0.0', '0', '0', '6.0', '0', '12', '177', '0', '0', '0', '0', '0', '0', '24000.0', '0', '0', '0'],
 ['George Washington', '0.0', '0', '0', '0.0', '0', '0', '214', '6', '0', '0', '0', '0', '0', '0', '0', '0', '0'],
 ['Barack Obama', '2.0', '0', '0', '2.0', '0', '0', '525', '3', '0', '0', '0', '0', '0', '24000.0', '20000.0', '94000.0', '114000.0']]