【发布时间】:2020-05-24 22:24:49
【问题描述】:
我的目标是以无序的方式存储来自用户的许多输入。所以,我决定使用set。我到目前为止的代码是:
a = input()
b = input()
c = input()
d = input()
all = a, b, c, d
print(set(all))
但是,我不想像上面那样多次重复input()。有没有办法做到这一点?
【问题讨论】:
标签: python python-3.x input set
我的目标是以无序的方式存储来自用户的许多输入。所以,我决定使用set。我到目前为止的代码是:
a = input()
b = input()
c = input()
d = input()
all = a, b, c, d
print(set(all))
但是,我不想像上面那样多次重复input()。有没有办法做到这一点?
【问题讨论】:
标签: python python-3.x input set
您可以将对 input() 的调用放在理解中:
set(input() for i in range(4))
【讨论】:
如果您只需要set,则不需要a, b, c, d。
all = set() #or all = {*(),}
for _ in range(4):
all.add(input())
print(all)
或者,
all = {input() for _ in range(4)}
这是考虑您在新行中输入。否则,如果输入以逗号分隔,例如:
all = set(input().split(','))
print(all)
或
all = {*input().split(',')}
print(all)
如果您同时需要 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
正如@Tomerikoo 所指出的,all(iterable) 是built-in function,避免将变量命名为与 python 内建或关键字相同。
还有一点,如果您已经这样做了,为了获得所有人的默认行为,您可以这样做:
>>> import builtins
>>> all = builtins.all
# Or, more conveniently, as pointed out by @Martijn Pieters
>>> del all
* 用于iterable unpacking
_ 用于don't care 或throwaway 或anonymous variable,
因为我们不需要循环中的变量。更多关于这个
here。{*()} 只是创建空集的一种奇特方式,因为 python 没有空集文字。推荐使用set()
【讨论】:
del all。内置是一个单独的命名空间。
你可以使用 for 循环:
all = set()
for _ in range(4):
all.add(int(input())
print(all)
不要忘记输入会为您提供一个字符串,因此您应该将其转换为 int 或任何需要的类型。
for 循环中的“_”表示这个变量不重要。但是你可以输入任何你喜欢的名字。
【讨论】: