简体   繁体   English

Python中元组列表的总长度

[英]Total length of a tuple list in Python

I'm working on an exercise where I need to display the number of previous faculties in a joint faculty and the number of schools in the joint faculty. 我正在做一个练习,其中需要显示联合学院以前的教师数量和联合学院的学校数量。

I've successfully completed those steps and the problem I'm having is working out how I can print the: 我已经成功完成了这些步骤,而我遇到的问题是如何打印:

4 5 4 5

together as '9' as a total instead of individually printing the lengths of the tuple separately. 总共作为'9'一起使用,而不是分别打印元组的长度。

I've been looking online everywhere for solutions but can't seem to find any solutions that work. 我一直在网上寻找解决方案,但似乎找不到任何有效的解决方案。

Below is my current code: 下面是我当前的代码:

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)

len returns an integer, so you can add them together len返回一个整数,因此您可以将它们加在一起

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

You could also add the two tuples together, then take the length of the resulting tuple like len(school1 + school2) . 您也可以将两个元组加在一起,然后取结果元组的长度,如len(school1 + school2) Adding tuples concatenates them. 添加元组将它们串联在一起。

You may use reduce : 您可以使用reduce

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

Just unpack them in one tuple as argument to len. 只需将它们拆成一个元组作为len的参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM