擅长:python、mysql、java
<p>这是我的解决方案,我想把这个问题的第一个版本,如果你不想使用熊猫:</p>
<pre><code>#!/usr/bin/env python
import re
data = """
XYZ
XYZ
ABC
ABC
MNP
MNP
Fruit
Apple
price
30
Number
10
Fruit
kiwi
Number
20
Fruit
grape
price
12"""
def doit(data):
table = []
data = re.split(r'\s+', data)
currentFruit = None
while len(data):
line = data.pop(0)
if line == "Fruit":
if currentFruit:
table.append(currentFruit)
currentFruit = { 'name': data.pop(0) }
elif currentFruit:
currentFruit[line] = data.pop(0)
table.append(currentFruit)
print "%-9s%-9s%-9s" % ("Fruit", "price", "Number")
for fruit in table:
print "%-9s%-9s%-9s" % (fruit['name'],
fruit['price'] if 'price' in fruit else '',
fruit['Number'] if 'Number' in fruit else '')
doit(data)
</code></pre>