python - Execute Pop, Discard and Remove commands on Sets
问题描述
If someone can help to understand the following eval logic and how the particular method is applied in this scenario.
n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
eval('s.{0}({1})'.format(*input().split()+['']))
print(sum(s))
The above code works absolutely fine and I'm trying to understand how the function works in details.
Here is the reference to the problem.
解决方案
欢迎来到stackoverflow。如果您是 Python 初学者,我建议您阅读Python 文档,它们为理解 Python 提供了很好的资源。
对于这个问题,你需要阅读https://docs.python.org/3/library/functions.html
好的,让我们逐行分解代码。
n = int(input())
从标准输入获取输入字符串,然后将其转换为int
数据类型。然后将其存储到变量n
s = set(map(int, input().split()))
获取输入,并将其拆分为每个空格。例如,如果输入是1 2 3
,它将是 的列表[1, 2, 3]
。然后,将列表中的每个元素转换为 int 数据类型。然后,将列表转换为集合。然后将其存储到变量s
中。
for i in range(int(input())):
从 0 迭代到输入的字符串并转换为 int 数据类型i
eval('s.{0}({1})'.format(*input().split()+['']))
好的,这会有点棘手。
首先,尝试了解 Python 格式,我建议您阅读https://pyformat.info/。总之,"string {0}, {2}, {1}".format("a", "b", "c")
会给你一串"string a, c, b"
.
在这种情况下,格式将采用 2 个参数,因为字符串中有{0}
和,它来自语句。{1}
's.{0}({1})'
*input().split()+['']
Python 将input().split()
首先执行,获取输入并将其拆分为列表。然后将该列表与另一个列表合并,即['']
. 之后,将列表元素作为格式的参数展开。
例如,如果您有输入
remove 9
它会像这样调用格式
's.{0}({1})'.format("remove", "9", "")
# will be
's.remove(9)'
"remove 9" -> ["remove", "9"] -> ["remove", "9", ""] -> "remove", "9", "" (as function argument)
好的,但有什么+['']
用?对于只有一个单词的输入格式化程序来说,这是一个技巧。
例如
's.{0}({1})'.format("pop", "")
# will be
's.pop()'
eval 函数接受一个参数,即字符串。它会将字符串作为 Python 代码执行。因此,eval("print(1)")
将打印1
到控制台。
print(sum(s))
打印集合的总和s
我希望我解释得足够清楚
推荐阅读
- apache-storm - 启动风暴雨云命令不起作用
- youtube-api - 可以发送到 YT 视频 API 的 ID 列表的最大可能长度是多少?
- .htaccess - Joomla Gzip 压缩仅在主页中工作
- c# - SignalR 集线器不响应对象参数
- python - 如何从 .trace 文件中提取方法调用信息?
- javascript - 使用 Sequelize 在数据库中创建新列?
- ms-access-2007 - Access 2007 不会打开 accdb 文件,除非它被重命名
- r - 根据第一次出现更改组中的值
- javascript - 构建 Web 应用程序时如何绕过客户端的 cors 错误?
- odata - 将标头添加到有效负载中的单个调用