简体   繁体   中英

Arithmetic operators on lists/tuples in Python?

I have a couple functions like this:

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

So I am using these to create this function:

collection obj.getChildren()

I am flexible in the return type, but I will doing a lot of "subtraction", "multiplication" using another list. So something like this:

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]

Is there a fast and elegant way to do these or do I have to go through each element one by one and gather the elements manually?

You're looking for set s

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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