<p>收集列表中的行,同时将该列表存储在字典中:</p>
<pre><code>d = {}
values = None
with open(filename) as inputfile:
for line in inputfile:
line = line.strip()
if line.startswith('Clutch'):
values = d[line] = []
else:
values.append(line)
</code></pre>
<p>这将为您提供:</p>
^{pr2}$
<p>不过,在加载文件后,很容易将所有这些列表转换为单个字符串:</p>
<pre><code>d = {key: ', '.join(value) for key, value in d.items()}
</code></pre>
<p>您也可以在读取文件时进行连接;我将使用生成器函数分组处理文件:</p>
<pre><code>def per_clutch(inputfile):
clutch = None
lines = []
for line in inputfile:
line = line.strip()
if line.startswith('Clutch'):
if lines:
yield clutch, lines
clutch, lines = line, []
else:
lines.append(line)
if clutch and lines:
yield clutch, lines
</code></pre>
<p>然后把所有的组都放到字典里:</p>
<pre><code>with open(filename) as inputfile:
d = {clutch: ', '.join(lines) for clutch, lines in per_clutch(inputfile)}
</code></pre>
<p>后者演示:</p>
<pre><code>>>> def per_clutch(inputfile):
... clutch = None
... lines = []
... for line in inputfile:
... line = line.strip()
... if line.startswith('Clutch'):
... if lines:
... yield clutch, lines
... clutch, lines = line, []
... else:
... lines.append(line)
... if clutch and lines:
... yield clutch, lines
...
>>> sample = '''\
... Clutch001
... Albino X Pastel
... Bumble Bee X Albino Lesser
... Clutch002
... Bee X Fire Bee
... Albino Cinnamon X Albino
... Mojave X Bumble Bee
... Clutch003
... Black Pastel X Banana Ghost Lesser
... '''.splitlines(True)
>>> {clutch: ', '.join(lines) for clutch, lines in per_clutch(sample)}
{'Clutch001': 'Albino X Pastel, Bumble Bee X Albino Lesser', 'Clutch002': 'Bee X Fire Bee, Albino Cinnamon X Albino, Mojave X Bumble Bee', 'Clutch003': 'Black Pastel X Banana Ghost Lesser'}
>>> from pprint import pprint
>>> pprint(_)
{'Clutch001': 'Albino X Pastel, Bumble Bee X Albino Lesser',
'Clutch002': 'Bee X Fire Bee, Albino Cinnamon X Albino, Mojave X Bumble Bee',
'Clutch003': 'Black Pastel X Banana Ghost Lesser'}
</code></pre>