我正在做一个练习,需要显示联合学院以前的教师数量和联合学院的学校数量。
我已经成功完成了这些步骤,而我遇到的问题是如何打印:
4 5
总计为“ 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)
答案 0 :(得分:2)
len
返回一个整数,因此您可以将它们加在一起
school1_len = len(school1) # 4
school2_len = len(school2) # 5
total = school1_len + school2_len
print(total)
您还可以将两个元组加在一起,然后取所得元组的长度,例如len(school1 + school2)
。添加元组将它们串联起来。
答案 1 :(得分:0)
您可以使用reduce
:
>>> l = (1, 2, 3), (4, 5), (6, 7, 8)
>>> reduce ((lambda x, y: x + len(y)), [0] + list (l))
8
答案 2 :(得分:0)
只需将它们拆成一个元组作为len的参数。
>>> school1 = ('social sciences', 'business', 'law', 'philosophy')
>>> school2 = ('maths', 'physics', 'computer science', 'chemistry',
... 'biology')
>>> len((*school1,*school2))
9