简体   繁体   中英

Subtracting sets in Python3 and getting output in list format

I have 2 sets:

A = [2,2,2,3,5,4]
B = [2]

I want to remove all 2's from A . I am doing this by subtracting B from A , and I need the output in a list format. So, I did the following:

y = list(set(A) - set(B))

However, it says:

TypeError: 'list' object is not callable

If I use y = list[set(CLI) - set(x)] , it says:

TypeError: list indices must be integers or slices, not set

Any suggestions, how I could get the output in the list format?

This could also work.

a = [2, 2, 2, 3, 5, 4]
b = [2]
def subtract_lists(a, b):
    for i in b:
        while i in a:
            a.remove(i)
    return a
print (subtract_lists(a, b))

Output [3, 5, 4]

It works fine on my computer:

A = [2,2,2,3,5,4] 
B = [2]
y = list(set(A) - set(B))
print(y)

Output:

[3, 4, 5]

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