Python中元组列表的总长度

2024-04-20 10:27:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个练习,我需要显示联合学院以前的院系数量和联合学院的学校数量。你知道吗

我已经成功地完成了这些步骤,现在的问题是如何打印:

4个 五

一起作为“9”作为总计,而不是单独打印元组的长度。你知道吗

我一直在网上到处寻找解决方案,但似乎找不到任何有效的解决方案。你知道吗

以下是我目前的代码:

school1 = ('social sciences', 'business', 'law', 'philosophy')
school2 = ('maths', 'physics', 'computer science', 'chemistry', 
'biology')

previous = school1, school2
print('Number of previous faculties in the joint faculty: 
',len(previous))

print(len(school1))
print(len(school2))

for x in school1:
   print(x)

for y in school2:
   print(y)

Tags: infor数量len步骤解决方案学校学院
3条回答

您可以使用^{}

>>> l = (1, 2, 3), (4, 5), (6, 7, 8)
>>> reduce ((lambda x, y: x + len(y)), [0] + list (l))
8

只需将它们解包成一个元组,作为len的参数。你知道吗

>>> school1 = ('social sciences', 'business', 'law', 'philosophy')
>>> school2 = ('maths', 'physics', 'computer science', 'chemistry', 
... 'biology')
>>> len((*school1,*school2))
9

len返回一个整数,因此可以将它们相加

school1_len = len(school1) # 4
school2_len = len(school2) # 5
total = school1_len + school2_len
print(total)

您也可以将两个元组相加,然后取结果元组的长度,如len(school1 + school2)。添加元组将它们连接起来。你知道吗

相关问题 更多 >