【发布时间】:2018-09-26 21:59:34
【问题描述】:
所以我想得到这个输出
No Column Sum
0 Company 28
1 Booth 28
2 Full-Time 25
3 Full-Time Visa Sponsor 5
4 Part-Time 1
5 Internship 18
6 Freshman 7
7 Sophomore 9
8 Junior 17
9 Senior 24
10 Post-Bacs 17
11 MS 17
12 PhD 6
13 Alumni 15
但是,我收到了这个错误
TypeError: 元组索引必须是整数或切片,而不是 str
我的代码如下
data_employer = {'No': ('Column', 'Sum')}
for vari in range(14):
sum = 0
for row in ReadyColumn:
if row[vari] != '':
sum =+1
data_employer = (companies[vari], sum)
for num in data_employer:
print(num, data_employer [num][0], data_employer[num][1])
outData = []
是不是因为我不需要调用 num 而是调用行号?我认为它可以这样工作。任何输入将不胜感激。谢谢!
Traceback (most recent call last):
File "/Prj3Assignt3.py", line 42, in <module>
print(num, data_employer[num][0], data_employer[num][1])
TypeError: tuple indices must be integers or slices, not str
添加错误
import csv
filename = "CFSpring2018Employers.csv" #I assigned the file to a variable
f = open(filename) #I couldn't leave it default due to UTF-8 error from orginial
reader = csv.reader(f)
f.close
#Dictionary for part 1 'Companies'
companies = {}
countComp = 0 #Sets the 'rows to 0
for row in reader: #reader has assigned value to read csv info
if row[0] == 'Company': #Searches row called 'Company'
for item in row:
companies[countComp] = item #Everytime it shows it puts it into the dictionary
countComp += 1
break
for i in companies: #Allows me to print numbers next to the companies dict
print(i, companies[i])
ReadyColumn = [] #Making a new list for cleaned up data
NumCow = 0
for row in reader:
NumCow +=1
if NumCow > 0 and NumCow < 31 and row[0] != '': #This will read the rows between 0-31, and if the row contains 'Nothing' it skips
ReadyColumn.append(row) #Updates the list
rowNum = -1 #Resets the counter
for row in ReadyColumn:
rowNum += 1
print(rowNum, ','.join(row)) #Joins any weird marks and prints as desired output
data_employer = {'No', 'Column', 'Sum'}
for vari in range(14):
sum = 0
for row in ReadyColumn:
if row[vari] != '':
sum =+1
cleaner_employer = (companies[vari], sum)
for i in data_employer:
print(i, data_employer,i[0], data_employer,i[1])
这是我为帮助实现这一点而编写的代码。我正在读取没有 PANDAS 的 csv 文件(因为我不能将它们用于项目)
【问题讨论】:
-
请在完整堆栈跟踪中发布实际错误的 sn-p。
-
好的更新有错误
标签: python csv dictionary tuples