2 回答

TA貢獻1795條經驗 獲得超7個贊
歡迎來到計算器。如果您是 Python 的初學者,我建議您閱讀Python 文檔,它們為理解 Python 提供了很好的資源。
對于這個問題,你需要閱讀https://docs.python.org/3/library/functions.html
好的,讓我們逐行分解代碼。
n = int(input())
從 stdin 獲取輸入字符串,然后將其轉換為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 個參數,因為string 中有{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
我希望我解釋得足夠清楚

TA貢獻1744條經驗 獲得超4個贊
這也是一個很好的替代解決方案:
n = int(input())
s = set(map(int, input().split()))
d = {"pop":s.pop, "remove":s.remove, "discard": s.discard}
for _ in range(int(input())):
c = input().split()
d[c[0]](int(c[1])) if len(c)>1 else d[c[0]]()
print(sum(s))
添加回答
舉報