如何在列表中拆分列表中的项目(带分隔符)?

2024-09-24 04:18:23 发布

您现在位置:Python中文网/ 问答频道 /正文

更新:抱歉,伙计们,我想说的是一个列表,在一个列表中。你知道吗

如何使用分隔符将列表中的项目拆分为另一个列表中的项目。例如:

x = [['temp1_a','temp2_b', None, 'temp3_c'],['list1_a','list2_b','list3_c']]

理想情况下,我想把它们分成一本字典,所以:

y = ['temp1','temp2', None, 'temp3','list1','list2','list3']
z = ['a','b', None, 'c','a','b','c']

我确信它使用了split,但是当我尝试使用它时,我得到的“list”对象没有属性“split”。你知道吗


Tags: 项目none列表字典情况split分隔符理想
3条回答

使用列表理解。你知道吗

>>> x = ['temp1_a','temp2_b', None, 'temp3_c']
>>> y, z  = [i if i is None else i.split('_')[0] for i in x ], [i if i is None else i.split('_')[1] for i in x ]
>>> y
['temp1', 'temp2', None, 'temp3']
>>> z
['a', 'b', None, 'c']

更新:

>>> x = [['temp1_a','temp2_b', None, 'temp3_c'],['list1_a','list2_b','list3_c']]
>>> y, z = [i if i is None else i.split('_')[0] for i in itertools.chain(*x)], [i if i is None else i.split('_')[1] for i in itertools.chain(*x) ]
>>> y
['temp1', 'temp2', None, 'temp3', 'list1', 'list2', 'list3']
>>> z
['a', 'b', None, 'c', 'a', 'b', 'c']

有很多方法可以做到这一点。。。你知道吗

>>> from itertools import chain
>>> y, z = zip(*([None]*2 if not i else i.split('_') for i in chain(*x)))
>>> y
('temp1', 'temp2', None, 'temp3', 'list1', 'list2', 'list3')
>>> z
('a', 'b', None, 'c', 'a', 'b', 'c')

下面是如何使用^{}

xp = [(None,)*2 if i is None else i.split('_') for i in x]
y, z = map(list, zip(*xp))

第二行右侧的表达方式只是一种优雅的书写方式:

[i[0] for i in xp], [i[1] for i in xp]

相关问题 更多 >