簡體   English   中英

Python中的列表/元組上的算術運算符?

[英]Arithmetic operators on lists/tuples in Python?

我有幾個這樣的功能:

object obj.getChild(childIndex)
int obj.numChildren()

所以我用這些來創建這個功能:

collection obj.getChildren()

我在返回類型上很靈活,但是我會使用另一個列表來做很多“減法”,“乘法”。 所以像這樣:

children = obj.getChildren()
children = [5,10,15,20,25]

globalChildren = [1,2,3,4,5,6,7,8,9,10,12,14,16,18,20]

difference = children - globalChildren
difference = [15,25]

shared = children * globalChildren
shared = [5,10,20]

是否有一種快速而優雅的方法來執行這些操作,還是我必須逐一遍歷每個元素並手動收集這些元素?

您正在尋找set

children = {5,10,15,20,25}

globalChildren = {1,2,3,4,5,6,7,8,9,10,12,14,16,18,20}

difference = children - globalChildren
shared = children & globalChildren

暫無
暫無

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

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