【问题标题】:How do you add or strip a new line based on a condition in Python?如何根据 Python 中的条件添加或删除新行?
【发布时间】:2021-06-09 22:50:18
【问题描述】:

我有以下列表:

b = ['B-PER 0 3 Joe', 'B-LOC 13 20 Angola', 'B-ORG 28 35 ABC', 'I-ORG 37 52 Financial', 'I-ORG 54 59 Center', 'B-LOC 72 80 Angola']

如果列表中的项目不以“I-”开头,我想将列表中的每个项目写入一个字符串并创建一个新行。如果项目确实以“I-”开头,我想将该行加入上一行。

我能得到的最接近的是以下:

a = ''
b = ['B-PER 0 3 Joe ', 'B-LOC 13 20 Angola ', 'B-ORG 28 35 ABC ', 'I-ORG 37 52 Financial ', 'I-ORG 54 59 Center ', 'B-LOC 72 80 Angola ']
for item in b:
    if not re.match(r'^I-.*', item):
        a += item + '\n'
    else:
        a += item.strip('\n')
        
print(a)

收到的输出:

B-PER 0 3 Joe 
B-LOC 13 20 Angola 
B-ORG 28 35 ABC 
I-ORG 37 52 Financial I-ORG 54 59 Center B-LOC 72 80 Angola

所需的输出:

B-PER 0 3 Joe 
B-LOC 13 20 Angola 
B-ORG 28 35 ABC I-ORG 37 52 Financial I-ORG 54 59 Center 
B-LOC 72 80 Angola

我猜这是我的条件逻辑和顺序的组合。任何解决方案将不胜感激!

【问题讨论】:

    标签: python for-loop if-statement conditional-statements


    【解决方案1】:

    对于这样的东西,有时更容易创建一个嵌套列表,根据需要添加项目,然后在完全构建后使用str.join()

    a = []
    b = ['B-PER 0 3 Joe ', 'B-LOC 13 20 Angola ', 'B-ORG 28 35 ABC ', 'I-ORG 37 52 Financial ', 'I-ORG 54 59 Center ', 'B-LOC 72 80 Angola ']
    for item in b:
        if not re.match(r'^I-.*', item):
            a.append([])
        a[-1].append(item)
    
    print('\n'.join(''.join(line) for line in a))
    # B-PER 0 3 Joe 
    # B-LOC 13 20 Angola 
    # B-ORG 28 35 ABC I-ORG 37 52 Financial I-ORG 54 59 Center 
    # B-LOC 72 80 Angola 
    

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 2021-12-07
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      相关资源
      最近更新 更多