![](/img/trans.png)
[英]how do i translate from s[-4:] to s[slice(???)] in python? not“ s[slice(s, len(s))]”
[英]What does this Python shorthand do? {s[:i] + s[i+1:] for s in level for i in range(len(s))}
level = {s[:i] + s[i+1:] for s in level for i in range(len(s))}
我認為它與此相同,但事實並非如此。
for s in level:
for i in range(len(s)):
level = {s[:i] + s[i+1:]}
資料來源: https : //leetcode.com/problems/remove-invalid-parentheses/discuss/75028/Short-Python-BFS
它在功能上等同於:
new_level = set()
for s in level:
for i in range(len(s)):
new_level.add(s[:i] + s[i+1:])
level = new_level
在實現這一目標時遇到的問題是
RuntimeError:在迭代期間設置更改的大小。 為了避免這種情況,我使用了copy()
功能level.copy()
另一方面,我們不能像在list,dict對象中那樣在Python中創建一個空集對象。 所以我們必須做一個絕對的實例化,因為new_level=set()
new_level=set() level={"one","two","three"} for s in level.copy(): for i in range(len(s)): new_level.add(s[:i] + s[i+1:]) print(new_level)
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.