所以基本上我需要读入一个文件,并逐列显示结果,下面显示了示例输入和输出以及我的代码。
这是txt文件:
Name ID City Favorite Fruit
Benjamin 5 Copenhagen kiwi
Tom 100 Kingston "watermelon, apple"
Rosemary 20 Philadelphia "pineapple, mango"
Annie 95 East Setauket "blueberry, hawthorn"
Jonathan 75 Ithaca cherry
Kathryn 40 San Francisco "banana, strawberry"
这是输出:
Number of rows: 7
Number of columns: 4
Column 0: Name
1 Annie
1 Benjamin
1 Jonathan
1 Kathryn
1 Rosemary
1 Tom
Column 1: ID
1 5
1 20
1 40
1 75
1 95
1 100
Column 2: City
1 Copenhagen
1 East Setauket
1 Ithaca
1 Kingston
1 Philadelphia
1 San Francisco
Column 3: Favorite Fruit
1 "banana, strawberry"
1 "blueberry, hawthorn"
1 "pineapple, mango"
1 "watermelon, apple"
1 cherry
1 kiwi
下面是我的代码,我一直纠结于如何逐列打印表格:
import sys
def main():
alist =[]
data = open("a1input1.txt").read()
lines = data.split('\n')
totalline =len(lines)
print ("Number of low is: " + str(totalline))
column = lines[0].split('\t')
totalcolumn = len(column)
print ("Number of column is: " + str(totalcolumn))
for index in range(totalline):
column = lines[index].split('\t')
print (column)
main()
下面是我所做的:newlist.sort(),name列已排序,但ID列未排序。所有这些值都是从一个txt文件中读取的。我不明白为什么只有ID列没有排序?
Column 0: Name
Annie
Benjamin
Jonathan
Kathryn
Rosemary
Tom
Column 1: ID
100
20
40
5
75
95
我试图使用“str()”转换字符串,但结果相同
另一个提示。。。如果要在列而不是行上迭代,请使用^{} 来转置数据。我会留给你来获得正确格式的数据:
输出
上面假设Python 3是通过使用
print()
作为函数来判断的。。。您可以在内置的csv模块中使用python,从而为自己节省大量看起来糟糕的代码。
这将为您提供一个对象,您可以遍历该对象以获取值的dict。
你可以得到一个标题列表
好的,这里有一些提示:
相关问题 更多 >
编程相关推荐