首页 > 解决方案 > 按空格分割并添加值 - Python

问题描述

我有一个这样的清单,

sample_lsit = ['ST,PAT A V0068 04/18/19 07/02/19 54 7 0.00 70.42',
               'ST,PAT A V0068 04/18/19 07/02/19 54 8 0.00 70.42',
               'LK,LON J V0067 07/02/19 7 26 0.00 486.00',
               'LK,LON J V0074 07/02/19 7 28 0.00 194.00',
               'LN,BET W V0195 05/16/19 07/02/19 77 2 2.33 36.49',
               'LN,BET W V0195 05/16/19 07/02/19 77 3 2.38 33.16']

在值 3 和 4 中,缺少日期,就是这样。我想要None缺少日期的位置的值。我正在尝试按这样的空间拆分列表中的每个值,

for i in sample_lsit:
    print(i.split(' '))

我得到这样的输出,

['ST,PAT', 'A', 'V0068', '04/18/19', '07/02/19', '54', '7', '0.00', '70.42']
['ST,PAT', 'A', 'V0068', '04/18/19', '07/02/19', '54', '8', '0.00', '70.42']
['LK,LON', 'J', 'V0067', '07/02/19', '7', '26', '0.00', '486.00']
['LK,LON', 'J', 'V0074', '07/02/19', '7', '28', '0.00', '194.00']
['LN,BET', 'W', 'V0195', '05/16/19', '07/02/19', '77', '2', '2.33', '36.49']
['LN,BET', 'W', 'V0195', '05/16/19', '07/02/19', '77', '3', '2.38', '33.16']

但是,我需要这样的输出,

['ST,PAT', 'A', 'V0068', '04/18/19', '07/02/19', '54', '7', '0.00', '70.42']
['ST,PAT', 'A', 'V0068', '04/18/19', '07/02/19', '54', '8', '0.00', '70.42']
['LK,LON', 'J', 'V0067', None, '07/02/19', '7', '26', '0.00', '486.00']
['LK,LON', 'J', 'V0074', None, '07/02/19', '7', '28', '0.00', '194.00']
['LN,BET', 'W', 'V0195', '05/16/19', '07/02/19', '77', '2', '2.33', '36.49']
['LN,BET', 'W', 'V0195', '05/16/19', '07/02/19', '77', '3', '2.38', '33.16']

我怎样才能做到这一点?我一直在寻找这个空间分割并添加

标签: python-3.xsplit

解决方案


这并不难,令人讨厌的部分是您有三个空格用于缺少的条目,而不仅仅是两个。

sample_list = ['ST,PAT A V0068 04/18/19 07/02/19 54 7 0.00 70.42',
               'ST,PAT A V0068   04/18/19 07/02/19 54 8 0.00 70.42',
               'LK,LON J V0067   07/02/19 7 26 0.00 486.00',
               'LK,LON J V0074 07/02/19 7 28 0.00 194.00',
               'LN,BET W V0195 05/16/19 07/02/19 77 2 2.33 36.49',
               'LN,BET W V0195 05/16/19 07/02/19 77 3 2.38 33.16']
result = [[x if x else None for x in line.replace('   ', '  ').split(' ')] for line in sample_list]
for line in result:
    print(line)

输出:

['ST,PAT', 'A', 'V0068', '04/18/19', '07/02/19', '54', '7', '0.00', '70.42']
['ST,PAT', 'A', 'V0068', None, '04/18/19', '07/02/19', '54', '8', '0.00', '70.42']
['LK,LON', 'J', 'V0067', None, '07/02/19', '7', '26', '0.00', '486.00']
['LK,LON', 'J', 'V0074', '07/02/19', '7', '28', '0.00', '194.00']
['LN,BET', 'W', 'V0195', '05/16/19', '07/02/19', '77', '2', '2.33', '36.49']
['LN,BET', 'W', 'V0195', '05/16/19', '07/02/19', '77', '3', '2.38', '33.16']

由于列表理解可能会让 Python 初学者感到困惑,因此上面的一行相当于(或多或少)以下内容:

result = []
for line in sample_list:
    temp = []
    for x in line.replace('   ', '  ').split(' '): # replace three spaces with just two before splitting
        if x: # If x is not an empty string than we can add it
            temp.append(x)
        else: # else it is None
            temp.append(None)

推荐阅读