简体   繁体   中英

Set subtraction while casting lists and string

I have two lists of strings. When I cast two lists into set() then subtraction works properly.

>>> A = ['One', 'Two', 'Three', 'Four']
>>> B = ['One']
>>> print(list(set(A) - set(B)))
['Three', 'Two', 'Four']

However when variable B is a string and I cast it into set() then, the subtraction is not working.

>>> A = ['One', 'Two', 'Three', 'Four']
>>> B = 'One'
>>> print(list(set(A) - set(B)))
['One', 'Two', 'Three', 'Four']

Is anyone able to explain me if its a bug or expected behavior?

This is expected. It considers the string as an iterable and thus creates a set of all letters.

B = 'One'
set(B)
# {'O', 'e', 'n'}

You can clearly see it if you have letters in A :

A = ['One', 'Two', 'Three', 'Four', 'O', 'o', 'n']
B = 'One'

print(list(set(A) - set(B)))

Output: ['o', 'Two', 'One', 'Four', 'Three']

The set() function, when operating on a string, will generate a set of all characters:

print(set("ABC"))  # set(['A', 'C', 'B'])

If you want a set with a single string ABC in it, then you need to pass a collection containing that string to set() :

print(set(["ABC"]))  # set(['ABC'])

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