Jac*_*aib 2 python performance list-comprehension list python-3.x
有没有更快的方法
listOfClasses = [fooA, fooB, fooC]
setOfStrings = {c.string for c in listOfClasses}
newListOfClasses = []
for c in listOfClasses:
if c.string in setOfStrings:
newListOfClasses.append(c)
setOfStrings.remove(c.string)
Run Code Online (Sandbox Code Playgroud)
限制/警告:
listOfClasses:
newListOfClasses:
listOfClasses假设我有一堂课
class Foo(object):
def __init__(self,string):
self.string = string
Run Code Online (Sandbox Code Playgroud)
以及我想删除所有具有重复“字符串”实例变量的类的类列表
fooA = Foo("alice")
fooB = Foo("alice")
fooC = Foo("His Royal Highness The Prince Philip, Duke of Edinburgh, Earl of Merioneth, Baron Greenwich, Royal Knight of the Most Noble Order of the Garter, Extra Knight of the Most Ancient and Most Noble Order of the Thistle, Member of the Order of Merit, Grand Master and First and Principal Knight Grand Cross of the Most Excellent Order of the British Empire, Knight of the Order of Australia, Additional Member of the Order of New Zealand, Extra Companion of the Queen’s Service Order, Royal Chief of the Order of Logohu, Extraordinary Companion of the Order of Canada, Extraordinary Commander of the Order of Military Merit, Lord of Her Majesty’s Most Honourable Privy Council, Privy Councillor of the Queen’s Privy Council for Canada, Personal Aide-de-Camp to Her Majesty, Lord High Admiral of the United Kingdom.")
listOfClasses = [fooA, fooB, fooC]
Run Code Online (Sandbox Code Playgroud)
在这里,我想删除fooA或fooB(无论哪个),这样我就只剩下
listOfClasses = [fooB, fooC] # for example
Run Code Online (Sandbox Code Playgroud)
到目前为止,我有以下几点:
setOfStrings = {c.string for c in listOfClasses}
newListOfClasses = []
for c in listOfClasses:
if c.string in setOfStrings:
newListOfClasses.append(c)
setOfStrings.remove(c.string)
Run Code Online (Sandbox Code Playgroud)
对于上述我得到以下时间:
# len(listOfClasses) = 3
2.22 ms ± 24.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# len(listOfClasses) = 20
2.29 ms ± 119 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Run Code Online (Sandbox Code Playgroud)
在 dict 理解中使用字典的唯一键应该非常快:
list({cls.string: cls for cls in listOfClasses}.values())
Run Code Online (Sandbox Code Playgroud)
完整示例:
class Foo(object):
def __init__(self, string):
self.string = string
fooA = Foo("alice")
fooB = Foo("alice")
fooC = Foo("His Royal Highness")
listOfClasses = [fooA, fooB, fooC]
print(list({cls.string: cls for cls in listOfClasses}.values()))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
45 次 |
| 最近记录: |