简体   繁体   English

如何减少if / elif语句中的重复代码

[英]How to reduce repetitive code in if/elif statement

What would be a better way to do the following pattern? 什么是执行以下模式的更好方法?

for platform_id in previous_platform_ids:
    if self.series.get(platform_id):
        del self.series[platform_id]
    elif self.seasons.get(platform_id):
        del self.seasons[platform_id]
    elif self.episodes.get(platform_id):
        del self.episodes[platform_id]
    elif self.movies.get(platform_id):
        del self.movies[platform_id]
    elif self.bundles.get(platform_id):
        del self.bundles[platform_id]

Basically, I want to iterate through a bunch of ids and remove that id from the list that contains it. 基本上,我想遍历一堆ID,并从包含它的列表中删除该ID。

self.series.pop(platform_id,None)
self.seasons.pop(platform_id,None)
self.episodes.pop(platform_id,None)
self.movies.pop(platform_id,None)
self.bundles.pop(platform_id,None)

seems like it would do the same thing (or actually not quite this will delete it from all dictionaries it(the key) is present in not just, the first one it finds, your code will only delete the first instance it finds ... not sure if that is intentional) 似乎它会做同样的事情(或者实际上并不能完全从它(键)所在的所有字典中删除它,而是找到的第一个字典,您的代码只会删除找到的第一个实例...不知道这是否是故意的)

of coarse you could do something like 粗略的你可以做类似的事情

for content_type in content_types:
    getattr(self, content_type).pop(platform_id,None)

if you only wanted to delete the first one you found you could do 如果您只想删除第一个,则可以执行

 content_dicts = [self.series,self.seasons,self.episodes,self.movies,self.bundles]
 next(x.pop(platform_id,None) for x in content_dicts if platform_id in x)

One way to do it is to iterate through each content_type and use the getattr method to check if it's there: 一种实现方法是遍历每个content_type并使用getattr方法检查是否存在:

content_types = ['series', 'seasons', 'episodes', 'movies', 'bundles']
for url in previous_urls:
    for content_type in content_types:
        if getattr(self, content_type).get(url):
            del getattr(self, content_type)[url]
            break

What about: 关于什么:

dicts = [self.series, ..., ]
remove_id_func = lambda _id: map(lambda dct: dct.pop(_id, None), dicts)

Somehow keeping them in a list seems nicer, and now use it like this: 以某种方式将它们保留在列表中似乎更好,现在像这样使用它:

remove_id_func(some_id)

An even nicer thing is to keep them in a mapping: 更好的事情是将它们保留在映射中:

dicts = {
    "series": self.series,
    "movies": self.movies,
    ...
}

And the remove function now becomes: 现在,删除功能变为:

remove_id_func = lambda _id: map(lambda kv: kv[1].pop(_id, None), dicts.items())

You can use class methods with simple loops which is probably better than these one-liners which are unmaintainable. 您可以将类方法与简单的循环一起使用,这可能比这些难以维护的单线更好。

Note that these operations remove the element from all lists, which is what you probably want. 请注意,这些操作可能会从所有列表中删除该元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM