用于将行转换为列的python查询

时间:2014-03-19 23:13:22

标签: python

我是stdin的输入

macys 100
sears 20
Boscov's 5
JCPenney 21
Kohl's 22
Others 16

此列表将会增长。

我想要输出如下

macys sears Boscov's JCPenney Kohl's Others 
100    20   5         21       22     16

4 个答案:

答案 0 :(得分:0)

正如大家都提到的那样使用cols = zip(*rows)例如...

some_text = """
macys 100
sears 20
Boscov's 5
JCPenney 21
Kohl's 22
Others 16
"""
#perhaps for you it will be some_text = sys.stdin.read()


#first convert it to a python list
some_list = some_text.splitlines()

#get rid of any empty lines
filtered_list = filter(None,some_list)

#split each line in half
rows_of_data = [line.split() for line in filtered_list]

#transpose it (turn it sideways)
headers,data = zip(*rows_of_data)


#print it out how you want
print "\n".join((" ".join(headers),
 " ".join("%-*s"%(len(headers[i]),value) for i,value in enumerate(data))))

答案 1 :(得分:0)

for line in stdin:
    a = line.split()
    list_a = a[0]
    list_b = a[1]
print list_a
print list_b

答案 2 :(得分:0)

datastring = """macys 100
sears 20
Boscov's 5
JCPenney 21
Kohl's 22
Others 16"""

converted = zip(*(line.split() for line in datastring.splitlines()))

converted是元组列表,每个元组都包含给定行中的项目。

您可以使用pandas外部库轻松操作数据:

import pandas as pd

dt = pd.DataFrame.from_records(converted[1:], columns=converted[0])
print dt

输出:

  macys sears Boscov's JCPenney Kohl's Others
0   100    20        5       21     22     16

答案 3 :(得分:0)

输入的实际格式为

{"Store":"Sears","count":10} 
{"Store":"Jcpenny","count":20} 
{"Store":"Macys","count":15} 
{"Store":"Others","count":0}