Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在基于字符分隔符将列表拆分为子列表时跳过空子字符串_Python_Python 3.x_String_List_Split - Fatal编程技术网

Python 如何在基于字符分隔符将列表拆分为子列表时跳过空子字符串

Python 如何在基于字符分隔符将列表拆分为子列表时跳过空子字符串,python,python-3.x,string,list,split,Python,Python 3.x,String,List,Split,我有以下清单 list_big = ['90', '=', 'C', '44', '='] 我想要的输出是在'='的事件之间连接所有字符串,如下所示: list_smaller = ['90', 'C44'] 我运行: list_smaller = [l.split(',') for l in ','.join(list_big).split('=')] 但我得到: list_smaller = [['90', ''], ['', 'C', '44', ''], ['']] 如何获得所需

我有以下清单

list_big = ['90', '=', 'C', '44', '=']
我想要的输出是在
'='
的事件之间连接所有字符串,如下所示:

list_smaller = ['90', 'C44']
我运行:

list_smaller = [l.split(',') for l in ','.join(list_big).split('=')]
但我得到:

list_smaller = [['90', ''], ['', 'C', '44', ''], ['']]

如何获得所需的输出?

您可以使用以下列表;使用空字符串而不是逗号连接,然后使用
if l
仅将非空字符串的元素放入列表中

>>> [l for l in ''.join(list_big).split('=') if l]
['90', 'C44']

这是因为您使用
,“
连接字符串,如果删除该字符串,您应该可以:

list_smaller = [i for i in ''.join(list_big).split('=') if i]
下次试着将你的理解列表分开,这样你就可以看到发生了什么:

list_big = ['90', '=', 'C', '44', '=']
joined_list_big = ','.join(list_big).split('=')
joined_list_big
['90,', ',C,44,', '']

在这里您可以看到这不是您想要的

您可以使用for循环:

new_list = []

aux = ''
for item in list_big:
    if item != '=':
        aux += item
    else:
        new_list.append(aux)
        aux = ''

if aux:
    new_list.append(aux)

print(new_list)
输出:

['90', 'C44']