簡體   English   中英

Python中元組列表的總長度

[英]Total length of a tuple list in Python

我正在做一個練習,其中需要顯示聯合學院以前的教師數量和聯合學院的學校數量。

我已經成功完成了這些步驟,而我遇到的問題是如何打印:

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)

len返回一個整數,因此您可以將它們加在一起

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

您也可以將兩個元組加在一起,然后取結果元組的長度,如len(school1 + school2) 添加元組將它們串聯在一起。

您可以使用reduce

>>> 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM