如何解决Python:TypeError:'float'对象不可迭代
在遍历元组列表时,我尝试使用为任何两行访问的值在 python 中进行计算,但我收到如下类型错误。有谁知道如何解决这个问题?谢谢!
代码如下:
for ws1 in ccy_results:
for ws2 in ccy_results:
variance = ws1.WS * ws2.WS
K += variance
错误信息:
K += variance
TypeError: 'float' object is not iterable
ccy_results 的摘录如下所示:
[ws(Qualifier='AUD',Curve='Libor3m',Tenor='1m',WS=214000000.0),ws(Qualifier='AUD',Tenor='2y',WS=-106000000.0),Tenor='6m',WS=213000000.0),ws(Qualifier='CHF',Curve='Libor6m',Tenor='15y',WS=-200000000.0),Tenor='20y',WS=540000000.0),Tenor='30y',WS=756000000.0)]
我尝试通过使用以下代码打印 ws1.WS 来进行检查,但是 ccy_results 中的所有 WS 都出现了。我想这就是原因。我该如何解决这个问题?
for ws1 in ccy_results:
for ws2 in ccy_results:
print(ws1.WS)
import collections
ws = collections.namedtuple('ws',('Qualifier','Curve','Tenor','WS'))
ccy_results = [ws(Qualifier='AUD',WS=756000000.0)]
K = []
for ws1 in ccy_results:
for ws2 in ccy_results:
variance = ws1.WS * ws2.WS
K += variance
解决方法
列表的增广赋值操作 awk ' ##Starting awk program from here.
FNR==NR{ ##Checking condition which will be TRUE when Input_file is being read first time.
arr[$NF]++ ##Creating arr with index of last field and increasing it 1 each time it comes with same one.
next ##next will skip all further statements from here.
}
arr[$NF]==1{ ##Checking condition if any value(last field) occurs only 1 time in whole Input_file then do following.
print > ("unique.txt") ##Printing current line to unique.txt output file.
next ##next will skip all further statements from here.
}
arr[$NF]>1{ ##Checking condition if last field comes more than 1 then do following.
outFile=$NF".txt" ##Creating outFile variable with last field .txt to it.
print >> (outFile) ##Printing current line to output file here.
close(outFile) ##Closing output file in backend to avoid "too many opened files" error.
}
' Input_file Input_file ##Mentioning Input_file(s) here.
等价于 +=
,它的参数(表达式的左侧)期望一个可迭代对象.
改变
list.extend
到
K += variance
操作 | 结果 |
---|---|
s.extend(t) 或 s += t | 用 t 的内容扩展 s(大部分与 s[len(s):len(s)] = t 相同) |
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。