当我尝试运行此代码时,我收到了这些错误
Traceback (most recent call last):
File "txt_square.py", line 7, in <module>`enter code here`
sqr = [elem **2 for elem in sqr_lst]
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
import csv
import math
with open('/home/amankumar/test.csv', 'rb') as fl:
reader = csv.reader(fl)
sqr_lst = list(reader)
sqr = [elem **2 for elem in sqr_lst]
print sqr
答案 0 :(得分:3)
csv reader对象包含作为项列表的行,并且如错误所示,您不能将**
操作数用于列表和整数。如果要在需要循环遍历行的项之间执行此操作。
您可以使用列表理解:
sqrs = [[i **2 for for i in elem] for elem in sqr_lst ]
然后结果将是所有项目的sqr的嵌套列表(每个嵌套列表是一行)