简体   繁体   English

在转换列表和字符串时设置减法

[英]Set subtraction while casting lists and string

I have two lists of strings.我有两个字符串列表。 When I cast two lists into set() then subtraction works properly.当我将两个列表转换为set()时,减法可以正常工作。

>>> 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.但是,当变量B是一个字符串并且我将其转换为set()时,减法不起作用。

>>> 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中有字母,您可以清楚地看到它:

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

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

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

The set() function, when operating on a string, will generate a set of all characters: set() function 在对字符串进行操作时,将生成一组所有字符:

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() :如果您想要一个包含单个字符串ABC的集合,那么您需要将包含该字符串的集合传递给set()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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