Python 不支持的操作数 int 和元组 - 试图从 Excel 范围创建列表
Python unsupported operand int and tuple - trying to create list from Excel range
这是一个使用 openpyxl 的 Python 问题:
我正在尝试将 'B2:B8' 中的一系列十进制数据加载到一个列表中,然后我可以对其进行数学运算。
我的问题:我不明白为什么我用来加载列表的代码在我尝试时会产生错误,例如总结一下。我想我没有正确加载它,但我不知道哪里出错了。感谢您提供的所有帮助(这里是初学者,很抱歉提出愚蠢的问题)。
import openpyxl
from openpyxl import load_workbook
#Open the excel file
wb = load_workbook('TestCase.xlsm', read_only=True)
sht = wb['Data']
#create first list that will hold weights
weightListd17 = []
#cycle through the Excel range
for wd17 in sht.iter_rows(min_row=2,
max_row=8,
min_col=2,
max_col=2,
values_only=True):
#load the range into my list
weightListd17.append(wd17)
print(weightListd17)
'''This looks like:
[(0.3746726857190015,), (0.07621196092466757,), (0.05527166764688042,),
(0.06828742220950017,), (0.1440061416059534,), (0.01962368942291444,),
(0.2619264324710826,)]
'''
#Test:
print(sum(weightListd17))
#ERROR:
'''
Traceback (most recent call last):
File "C:\Emma Code\ExtractList.py", line 28, in <module>
print(sum(weightListd17))
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
'''
当您迭代 sht.iter_rows
时,该值似乎为您提供了元组类型。您将使用 wd17
附加元组。避免的一种方法是修改行:
# since wd17 is tuple, so access the `int` with [0]
weightListd17.append(wd17[0])
这是一个使用 openpyxl 的 Python 问题: 我正在尝试将 'B2:B8' 中的一系列十进制数据加载到一个列表中,然后我可以对其进行数学运算。 我的问题:我不明白为什么我用来加载列表的代码在我尝试时会产生错误,例如总结一下。我想我没有正确加载它,但我不知道哪里出错了。感谢您提供的所有帮助(这里是初学者,很抱歉提出愚蠢的问题)。
import openpyxl
from openpyxl import load_workbook
#Open the excel file
wb = load_workbook('TestCase.xlsm', read_only=True)
sht = wb['Data']
#create first list that will hold weights
weightListd17 = []
#cycle through the Excel range
for wd17 in sht.iter_rows(min_row=2,
max_row=8,
min_col=2,
max_col=2,
values_only=True):
#load the range into my list
weightListd17.append(wd17)
print(weightListd17)
'''This looks like:
[(0.3746726857190015,), (0.07621196092466757,), (0.05527166764688042,),
(0.06828742220950017,), (0.1440061416059534,), (0.01962368942291444,),
(0.2619264324710826,)]
'''
#Test:
print(sum(weightListd17))
#ERROR:
'''
Traceback (most recent call last):
File "C:\Emma Code\ExtractList.py", line 28, in <module>
print(sum(weightListd17))
TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
'''
当您迭代 sht.iter_rows
时,该值似乎为您提供了元组类型。您将使用 wd17
附加元组。避免的一种方法是修改行:
# since wd17 is tuple, so access the `int` with [0]
weightListd17.append(wd17[0])