0
我有一個包含11列的CSV文件。我是Python新手,嘗試創建一個按字母順序排序列2的代碼,然後打印排序列表的行。根據python中的值打印排序的列
我只想要打印的行,其中第1個== 1
如果塔1 == 0然後我希望腳本忽略此行,並繼續到下一行,而不進行打印。
in_file = open('filename.csv', 'r')
dict = {}
#should print all rows where field [0] == 1
print('List of rows where column one is equal to zero in alphabetical order of column 2')
for line in in_file:
line = line.strip('\n')
fields = line.split(',')
c1 = fields[0]
c2 = fields[1]
c3 = fields[2]
c4 = fields[3]
c5 = fields[4]
c6 = fields[5]
c7 = fields[6]
c8 = fields[7]
c9 = fields[8]
c10 = fields[9]
c11 = fields[10]
if c2 not in dict:
dict[c2] = c1
if c3 not in dict:
dict[c3] = c1
if c4 not in dict:
dict[c4] = c1
if c5 not in dict:
dict[c5] = c1
if c6 not in dict:
dict[c6] = c1
if c7 not in dict:
dict[c7] = c1
if c8 not in dict:
dict[c8] = c1
if c9 not in dict:
dict[c9] = c1
if c10 not in dict:
dict[c10] = c1
if c11 not in dict:
dict[c11] = c1
name = dict.keys()
sorted_names = sorted(name)
for name in sorted_names:
c1 = dict[name]
rows = [row for row in in_file if row ['c1']!= 1]
for row in rows:
print(c3, c2, c4, c5)
in_file.close()
你能解釋一下問題所在嗎?你只是告訴我們你想要腳本做什麼 – 2016-05-17 05:41:47
嗨,我遇到的問題是行上的代碼錯誤rows = [行in_file中的行,如果行['survived']!= 1]和狀態TypeError:字符串索引必須是整數。 column1是一個整數,所以有點困惑。 – pops