【发布时间】:2021-04-29 14:27:26
【问题描述】:
【问题讨论】:
标签: python python-3.x string split
【问题讨论】:
标签: python python-3.x string split
lines = [line for line in txt.splitlines() if line]
for idx in range(0, len(lines), 2):
keys = lines[idx].split()
values = lines[idx+1].split()
for k, v in zip(keys, values):
print(f"{k}:{v}")
输出:
1.name:chandu
2.address:madhuranagr
3.option:234
4a.option1:345
4b.option2:456
4c.option3:789
【讨论】:
这是一个可能的解决方案:
# Gets an array where each entry is a line.
lines = txt.split('\n')
# Discard first and last lines, which are empty.
lines = lines[1:-1]
# Iterate over pairs of lines.
for i in range(len(lines)//2):
# Compute indices for the relevant lines
question_index = 2*i
answer_index = 2*i + 1
# Split the entries in a line, using strip() to remove the last (empty) entry.
question_parts = lines[question_index].strip().split(' ')
answer_parts = lines[answer_index].strip().split(' ')
# Print question-answer pairs.
for j in range(len(question_parts)):
# Skip questions without answers.
if j < len(answer_parts):
print('%s:%s' % (question_parts[j], answer_parts[j]))
它解决了那个特定的例子,但它不能处理所有的边缘情况:例如,是否有可能缺少中间答案之一?如果是,那么这种情况下的数据结构如何?
【讨论】: