如何将来自用户的许多输入存储在一个集合中

Olo*_*ade 4 python input set python-3.x

我的目标是以无序方式存储来自用户的许多输入。所以,我决定使用set. 我到目前为止的代码是:

a = input()
b = input()
c = input()
d = input()

all = a, b, c, d
print(set(all))
Run Code Online (Sandbox Code Playgroud)

但是,我不想像input()上面那样重复几次。有没有办法实现这一目标?

CDJ*_*DJB 9

您可以将您对 input() 的调用放在理解中:

set(input() for i in range(4))
Run Code Online (Sandbox Code Playgroud)


Cyt*_*rak 9

如果你想要的只是一个set你不需要的a, b, c, d.

all = set()   #or all = {*(),}
for _ in range(4):
    all.add(input())

print(all)
Run Code Online (Sandbox Code Playgroud)

或者,

all = {input() for _ in range(4)}
Run Code Online (Sandbox Code Playgroud)

这是考虑到您在新行中输入。否则,如果输入以逗号分隔,例如:

all = set(input().split(','))
print(all)
Run Code Online (Sandbox Code Playgroud)

或者

all = {*input().split(',')}
print(all)
Run Code Online (Sandbox Code Playgroud)

如果您需要a, b, c, d所有输入,您可以执行以下操作:

>>> all = a, b, c, d = {*input().split(',')}
# example
>>> all = a, b, c, d = {1, 2, 3, 4}
>>> all
{1, 2, 3, 4}
>>> a
1
>>> b
2
Run Code Online (Sandbox Code Playgroud)

正如@Tomerikoo 所指出的那样,all(iterable)是一个内置函数,避免将变量命名为与 python 内置函数或关键字相同的名称。还有一点,如果你已经这样做了,为了获得所有的默认行为,你可以这样做:

>>> import builtins
>>> all = builtins.all
# Or, more conveniently, as pointed out by @Martijn Pieters
>>> del all
Run Code Online (Sandbox Code Playgroud)
  • * 是用来 iterable unpacking
  • _用于don't carethrowaway或者anonymous variable,因为我们不需要在循环中的变量。更多关于 这里
  • {*()}只是一种创建空集的奇特方式,因为 python 没有空集文字。建议使用set()

  • 无需重新绑定全局,只需*删除它*:`del all`。内置函数是一个单独的命名空间。 (2认同)