首页 > 解决方案 > 您将如何比较两个字符串,以便它们可以循环并维护每个标题的项目?提供的示例

问题描述

我在打印这两个字符串(或仅一个字符串)时遇到问题,方法是将它们附加并分组到它们的标题中。新标头 (h*) 的指示是新组对的开始位置。

headers = ['h1', 'h2', 'h3']
full = ['h1','a','b','c','h2','d','e','f','h3','g','h','i','j','k']


print('h1' + ':' + 'a')
print('h1' + ':' + 'b')
print('h1' + ':' + 'c')
print('h2' + ':' + 'd')
print('h2' + ':' + 'e')
print('h2' + ':' + 'f')
print('h3' + ':' + 'g')
etc.

output:   
h1:a
h1:b
h1:c
h2:d
etc.

标签: python-3.xlistcompare

解决方案


# Initialize index to -1.
header_i = -1

# Go through each element.
for elem in full:
    # If element is in the headers list, update header index to element's index in headers.
    if elem in headers:
        header_i = headers.index(elem)
    # Else, print out the current header and element.
    else:
        print(headers[header_i], ':', elem)

推荐阅读