将行转换为列的python查询

2024-10-02 22:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我是stdin的输入

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

这个名单会越来越多。在

我想要下面这样的输出

^{pr2}$

Tags: stdin名单otherspr2macyssearsjcpenneykohl
3条回答
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外部库轻松操作数据:

^{pr2}$

输出:

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

正如每个人都提到过使用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))))
for line in stdin:
    a = line.split()
    list_a = a[0]
    list_b = a[1]
print list_a
print list_b

相关问题 更多 >