在python中查找嵌套元组中单个项的计数

在python中查找嵌套元组中单个项的计数,python,python-3.x,Python,Python 3.x,我有一个包含嵌套元组的元组。查找元组中单个项总数的最简单方法是什么。我正在使用python 3 元组看起来像 (('BCG', 'OPV 0', 'Hep-B 1'), ('DTwP 1', 'IPV 1', 'Hep-B 2', 'Hib 1', 'Rotavirus 1', 'PCV 1'), ('DTwP 2', 'IPV 2', 'Hib 2', 'Rotavirus 2', 'PCV 2'), ('DTwP 3', 'IPV 3', 'Hib 3', 'Rotavirus 3', 'P

我有一个包含嵌套元组的元组。查找元组中单个项总数的最简单方法是什么。我正在使用python 3

元组看起来像

(('BCG', 'OPV 0', 'Hep-B 1'), ('DTwP 1', 'IPV 1', 'Hep-B 2', 'Hib 1', 'Rotavirus 1', 'PCV 1'), ('DTwP 2', 'IPV 2', 'Hib 2', 'Rotavirus 2', 'PCV 2'), ('DTwP 3', 'IPV 3', 'Hib 3', 'Rotavirus 3', 'PCV 3'), ('OPV 1', 'Hep-B 3'), ('OPV 2', 'MMR-1'), ('Typhoid', 'Conjugate Vaccine'), 'Hep-A 1', ('MMR 2', 'Varicella 1', 'PCV booster'), ('DTwP B1/DTaP B1', 'IPV B1, Hib B1'), 'Hep-A 2', 'Typhoid booster', ('DTwP B2/DTaP B2', 'OPV 3', 'Varicella 2', 'Typhoid booster'), ('Tdap/Td', 'HPV'))

我想要元组中所有项目的总和如果您指的是整个数据集中的每个单独项目,您可以轻松地执行以下操作:

data = (('BCG', 'OPV 0', 'Hep-B 1'), ...)
unique = len(set(x for inner in data for x in inner))
就这样

它的工作原理是迭代每个内部元组,然后遍历每个元组中的每个项。将它们添加到一个集合(所有项目必须是唯一的),然后计算集合的大小


编辑:也许我误解了“单个项目”,我以为您希望忽略重复项。

您有一个元组的元组,并且想知道其中有多少个项目。这包括:

>>> t = (('BCG', 'OPV 0', 'Hep-B 1'), ('DTwP 1', 'IPV 1', 'Hep-B 2', 'Hib 1', 'Rotavirus 1', 'PCV 1'), ('DTwP 2', 'IPV 2', 'Hib 2', 'Rotavirus 2', 'PCV 2'), ('DTwP 3', 'IPV 3', 'Hib 3', 'Rotavirus 3', 'PCV 3'), ('OPV 1', 'Hep-B 3'), ('OPV 2', 'MMR-1'), ('Typhoid', 'Conjugate Vaccine'), 'Hep-A 1', ('MMR 2', 'Varicella 1', 'PCV booster'), ('DTwP B1/DTaP B1', 'IPV B1, Hib B1'), 'Hep-A 2', 'Typhoid booster', ('DTwP B2/DTaP B2', 'OPV 3', 'Varicella 2', 'Typhoid booster'), ('Tdap/Td', 'HPV'))
>>> sum(len(x) for x in t)
65

t
是元组中的元组
x
t
中的每个元组。这将对所有
x

的长度求和,如果相同的项出现在不同的元组中,是否仍要将它们作为单个项计数?
t = (('BCG', 'OPV 0', 'Hep-B 1'), ('DTwP 1', 'IPV 1', 'Hep-B 2', 'Hib 1', 'Rotavirus 1', 'PCV 1'), ('DTwP 2', 'IPV 2', 'Hib 2', 'Rotavirus 2', 'PCV 2'), ('DTwP 3', 'IPV 3', 'Hib 3', 'Rotavirus 3', 'PCV 3'), ('OPV 1', 'Hep-B 3'), ('OPV 2', 'MMR-1'), ('Typhoid', 'Conjugate Vaccine'), 'Hep-A 1', ('MMR 2', 'Varicella 1', 'PCV booster'), ('DTwP B1/DTaP B1', 'IPV B1, Hib B1'), 'Hep-A 2', 'Typhoid booster', ('DTwP B2/DTaP B2', 'OPV 3', 'Varicella 2', 'Typhoid booster'), ('Tdap/Td', 'HPV'))
sum(map(lambda  x:len(x),t))