我正在尝试a将列中的值乘以1.5
import csv
ids=[2,4,1,10,6,7,15,9]
names=["Joe","Steve","Samantha","Leah","Riley","Ashley","Sheyanne"]
salaries=[95000,35000.150000,99000,53215,23424,225000]
with open("q2.csv","w+",newline='') as file:
filewriter=csv.writer(file)
content=[ids,names,salaries]
zipped=zip(*content)
fieldnames=["id","name","salary"]
filewriter.writerow(fieldnames)
filewriter.writerows(zipped)
with open("q2.csv","r")as fileread:
reader=csv.reader(fileread)
next(reader,None)
listJ=[]
for row in reader:
if len(row[1])<=3 or row[1].startswith("S"):
listJ.append(row)
for row in listJ:
row[2]=row[2]*1.5
print(listJ)
它会产生这样的结果。
[['2', 'Joe', '9500095000'], ['4', 'Steve', '35000.1535000.15'], ['1', 'Samantha', '9900099000']]
我尝试使用
for id,name,salary in listJ:
salary=salary*1.5
这个给了我
>TypeError: can't multiply sequence by non-int of type 'float'
我什至尝试使用numpy.asarray使薪资列表浮动,但仍然无法正常工作。
谢谢
答案 0 :(得分:1)
salary字段以字符串形式读取,因此您需要先将其转换为数字类型:
salary = float(salary) * 1.5
或者:
row[2] = float(row[2]) * 1.5