串联属于某些值的列表元素之间的列表元素 [英] Concatenate list elements that fall between list elements of certain value
本文介绍了串联属于某些值的列表元素之间的列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一下,我有以下列表:
Imagine I have the following list:
>>> mylist
[('a', u'DT'),
('Satisfactory', u'JJ'),
('tracing', u'VBG'),
('with', u'IN'),
('a', u'DT'),
('fairly', u'RB'),
('persistent', u'JJ'),
('with', u'IN')]
如何串联属于包含u'IN'
或u'DT'
的元素之间的列表项,并且仅返回串联的元素,即:
How do I concatenate list items that fall between elements that contain u'IN'
or u'DT'
and return only the concatenated elements i.e:
[('Satisfactory tracing'),
('fairly persistent')]
推荐答案
以下是一种可以为您提供所需结果的工具.也许您需要对其进行一些优化.
Here is one which shall give you the desired result. Maybe you need to optimize it a bit.
my_list = ([('a', u'DT'),
('Satisfactory', u'JJ'),
('tracing', u'VBG'),
('with', u'IN'),
('a', u'DT'),
('fairly', u'RB'),
('persistent', u'JJ'),
('with', u'IN')])
sequence_enable = False
new_list = []
for i in my_list:
if i[1] == 'DT' or i[1] == 'IN':
if not sequence_enable: # Start reading values
sequence_enable = True
temp_str = []
else: # stop reading values
new_list.append(' '.join(temp_str))
sequence_enable = False
continue
else: # store values
if sequence_enable:
temp_str.append(i[0])
print(new_list)
# output: ['Satisfactory tracing', 'fairly persistent']
这篇关于串联属于某些值的列表元素之间的列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文