在我的案例中,替换 switch 语句的最有效方法是什么?
What is the most efficient way to to replace switch statement in my case?
我需要在一个大列表中搜索和排序大量数据,然后将它们排序到 python 3.5 中的其他列表中。
当我完成编码时,我意识到如果我只需要检查 biglist 中的项目,我应该使用 switch 语句来使我的代码更高效。说到 python,我处于初级水平。我在 python 3.5 中搜索了 switch 语句,令我震惊的是 python 中没有这样的语句。(我用 C 编写了一些代码,Java 和 JavaScript 并且它们都有 switch 语句,所以我认为这将是每种语言都必须存在的用于流控制的东西。)
我搜索 biglist 的代码部分目前看起来像这样:
for item in biglist:
if item == String1:
list1.append(biglist[biglist.index(item) + 1])
continue
#
#this goes on till String10 and ends like this
#
elif item == String10:
list10.append(biglist[biglist.index(item) + 1])
continue
else:
break
完成一个数据集的整个程序大约需要 12 个小时。我需要多做 4 次,但在我这样做之前,如果我还没有实现最有效的解决方案,我会喜欢一些关于如何使我的代码更高效和更快的建议甚至解决方案。
还请解释一下为什么该解决方案更有效,因为我想了解它。
效率低下与 "switch" 的存在与否无关,而是您使用 .index()
方法的事实,该方法会导致对列表进行全面扫描以查找您的项目。没有必要这样做,您可以使用 enumerate
函数 return 索引:
for index, item in enumerate(biglist):
if item == String1:
list1.append(biglist[index + 1])
性能问题很可能不是类似 switch 的 if 语句,而是在 O(n) (Complexity of list.index(x) in Python) 中运行的 biglist.index(item)
操作。
使用类似的东西:
for idx, item in enumerate(biglist):
print idx, item
跟踪项目的索引。
如果您仍然想替换 if 语句,您可以使用字典,其中为每个可能的项目值存储了一个列表。
这可以模仿switch
。
def switch(x):
return {
'String1': list1,
'String10' : list10
}.get(x)
for item in bigList:
try:
switch(item).append(biglist[biglist.index(item) + 1])
except AttributeError:
#Do some other work
我需要在一个大列表中搜索和排序大量数据,然后将它们排序到 python 3.5 中的其他列表中。 当我完成编码时,我意识到如果我只需要检查 biglist 中的项目,我应该使用 switch 语句来使我的代码更高效。说到 python,我处于初级水平。我在 python 3.5 中搜索了 switch 语句,令我震惊的是 python 中没有这样的语句。(我用 C 编写了一些代码,Java 和 JavaScript 并且它们都有 switch 语句,所以我认为这将是每种语言都必须存在的用于流控制的东西。)
我搜索 biglist 的代码部分目前看起来像这样:
for item in biglist:
if item == String1:
list1.append(biglist[biglist.index(item) + 1])
continue
#
#this goes on till String10 and ends like this
#
elif item == String10:
list10.append(biglist[biglist.index(item) + 1])
continue
else:
break
完成一个数据集的整个程序大约需要 12 个小时。我需要多做 4 次,但在我这样做之前,如果我还没有实现最有效的解决方案,我会喜欢一些关于如何使我的代码更高效和更快的建议甚至解决方案。
还请解释一下为什么该解决方案更有效,因为我想了解它。
效率低下与 "switch" 的存在与否无关,而是您使用 .index()
方法的事实,该方法会导致对列表进行全面扫描以查找您的项目。没有必要这样做,您可以使用 enumerate
函数 return 索引:
for index, item in enumerate(biglist):
if item == String1:
list1.append(biglist[index + 1])
性能问题很可能不是类似 switch 的 if 语句,而是在 O(n) (Complexity of list.index(x) in Python) 中运行的 biglist.index(item)
操作。
使用类似的东西:
for idx, item in enumerate(biglist):
print idx, item
跟踪项目的索引。
如果您仍然想替换 if 语句,您可以使用字典,其中为每个可能的项目值存储了一个列表。
这可以模仿switch
。
def switch(x):
return {
'String1': list1,
'String10' : list10
}.get(x)
for item in bigList:
try:
switch(item).append(biglist[biglist.index(item) + 1])
except AttributeError:
#Do some other work