python中的列表,做如下处理:取出部分连续的字符串进行合并,并放入一个新的列表,并返回这几个字符串在原列表中的索引,要求取出的字符串以B开头,结束的那个字符串以I开头,并且结束的字符串的下一个字符串要以B或者O开头,若字符串以B开头,下一个便是以B或者O开头,则只取出B,例如,对于列表a = ['B-ORG', 'I-ORG', 'I-ORG', 'O-TITLE', 'B-TITLE', 'I-TITLE', 'O-TITLE', 'O','B-ORG','O'],返回列表b=['B-ORGI-ORGI-ORG','B-TITLEI-TITLE','B-ORG']和列表c=
时间: 2023-09-01 14:07:27 浏览: 104
[0, 4, 9],表示取出的字符串在原列表中的索引为0,4,9。
可以使用以下代码实现:
```python
def merge_strings(a):
b = []
c = []
start_index = None
for i in range(len(a)):
if a[i].startswith("B"):
start_index = i
elif start_index is not None and a[i].startswith("I"):
if i == len(a) - 1 or (not a[i+1].startswith("I") and not a[i+1].startswith("B")):
end_index = i
b.append("".join(a[start_index:end_index+1]))
c.append(start_index)
start_index = None
elif start_index is not None:
end_index = i - 1
b.append("".join(a[start_index:end_index+1]))
c.append(start_index)
start_index = None
return b, c
```
例如:
```python
a = ['B-ORG', 'I-ORG', 'I-ORG', 'O-TITLE', 'B-TITLE', 'I-TITLE', 'O-TITLE', 'O','B-ORG','O']
b, c = merge_strings(a)
print(b)
print(c)
```
输出:
```
['B-ORGI-ORGI-ORG', 'B-TITLEI-TITLE', 'B-ORG']
[0, 4, 9]
```
其中,列表`b`是合并后的字符串列表,列表`c`是取出的字符串在原列表中的索引列表。
阅读全文
相关推荐

















