python-3.x - 您将如何比较两个字符串,以便它们可以循环并维护每个标题的项目?提供的示例
问题描述
我在打印这两个字符串(或仅一个字符串)时遇到问题,方法是将它们附加并分组到它们的标题中。新标头 (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.
解决方案
# 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)
推荐阅读
- python - 如果它们最初或交换后的位置在 Pandas 中相同,则将重复的行删除多列
- c# - 如何将整数值添加到日期并在c#中计算结束日期
- c# - 在 Blazor 页面的 OnInitializedAsync() 中访问 context.User
- reactjs - 如何使用类组件中的 react-router 链接从传递数据的组件中使用数据?
- amazon-web-services - 如何为所有 CloudFormation 嵌套堆栈保持相同的 API 网关 URL?
- java - 使用 Spring Boot 调用具有两个 INOUT 参数的 oracle 过程
- python - Panda Dataframe 查找 DataFrame 中没有等效值的行
- mongodb - 无法通过终端使用身份验证数据连接 mongodb
- python - 使用 pyenv 安装特定的 python 版本
- python - 如何在 Django 模板中加载图表