我目前有一个元组列表,我正在尝试计算列表中的元组数量,这样我就可以进行其他计算,但我似乎无法使其工作。
ties = [(84,40,{'variable1' : 0.11225, 'variable2': -0.2581}),
(84,4,{'variable1' : -0.18855, 'variable2': -0.6458}),
(84,23,{'variable1' : 0.05144, 'variable2': -0.7581})]
ties = list((int(j) for i in ties for j in i))
res = len(ties)
#alternatively I also tried
from itertools import chain
res = len(list(map(int, chain.from_iterable(ties))))
以上(两者(都会抛出一个错误TypeError: 'int' object is not iterable
,我不明白为什么。想法?
提前感谢!
***编辑***
修复了语法错误,现在它工作了,感谢大家的建议
元组不能迭代。因此,在尝试执行代码时会出现错误。此外,您发布的以下代码出现语法错误。
ties = [(84,40,{'variable1' : 0.11225, 'variable2': -0.2581}), 84,4,{'variable1' : -0.18855, 'variable2': -0.6458}), 84,23,{'variable1' : 0.05144, 'variable2': -0.7581})]
您似乎错过了84,4之前的左括号,以及84,23之后的左括号。
尝试以下操作:
ties = [(84,40,{'variable1' : 0.11225, 'variable2': -0.2581}), (84,4,{'variable1' : -0.18855, 'variable2': -0.6458}), (84,23,{'variable1' : 0.05144, 'variable2': -0.7581})]
ties_len = list((len(i) for i in ties))
由isinstance
过滤的列表理解,假设ties
实际上是以下对象(因为OP是无效语法(
ties = [
(84,40,{'variable1' : 0.11225, 'variable2': -0.2581}),
(84,4,{'variable1' : -0.18855, 'variable2': -0.6458}),
(84,23,{'variable1' : 0.05144, 'variable2': -0.7581})
]
count_tuples = len([o for o in ties if isinstance(o, tuple)])
打印:3
如果你只是想知道列表中元组的数量,你只需要这个:
ties = [
(84,40,{'variable1' : 0.11225, 'variable2': -0.2581}),
(84,4,{'variable1' : -0.18855, 'variable2': -0.6458}),
(84,23,{'variable1' : 0.05144, 'variable2': -0.7581})
]
res = len(ties)
# 3
如果你想要一个包含列表中元组长度的列表,你需要使用:
res = [len(tie) for tie in ties]
# [3, 3, 3]