Skip to main content
 首页 » 编程设计

python之索引、for 循环和让事情看起来更干净

2025年05月04日19jpfss

我有许多对象代表一封信的不同版本。其中一些版本已经打印(时间戳)。如果打印了一封信(及其所有版本),我需要获取最后打印版本的时间戳(很容易完成),然后是最后打印版本的版本号(目前使我的代码看起来像 C++{shiver} ).

那么我如何使它看起来更像 pythonic(更干净)

try: 
    # get the lastest letter version that has been printed 
    lv_temp = LV.objects.filter(letter=letter.id,printed_last__isnull=False).latest('id') 
    # get the id's of all the letter versions for a particular letter 
    lv_temp2 = LV.objects.filter(letter=letter.id).order_by('id') 
    lv_temp4 = [] 
    # get all the letter version for a particular letter 
    for lv_temp3 in lv_temp2: 
        lv_temp4.append(lv_temp3.id) 
    # get an array of the indexes and the pks 
    for i,v in enumerate(lv_temp4) : 
        # if the pk of the last printed version is the same one as in the loop... 
        if lv_temp.id == v : 
            # ...save the index as the version number 
            lv_printed_ver = i 
    lv_printed = lv_temp.printed_last 
except ObjectDoesNotExist: 
    lv_printed = None 
    lv_printed_ver = None 

(我使用了 lv_temp... 因为有多少次我不得不传递东西,我很生气)

请您参考如下方法:

生成 id 列表的更 pythonic 方法是列表理解,替换

lv_temp2 = LV.objects.all().order_by('id') 
lv_temp4 = [] 
for lv_temp3 in lv_temp2: 
    lv_temp4.append(lv_temp3.id) 

与

lv_temp4 = [i.id for i in LV.objects.all().order_by('id')] 

然后,假设我正确理解了你的代码,并且你正在寻找列表中与 id 匹配的索引,你可以这样做:

lv_printed_ver = lv_temp4.index(lv_temp.id) 

HTH