如何使用 if 条件以不同的迭代方式执行相同的命令? (Python,代码优化)

How to do same commands but in different iteration styles with if-condition? (Python, code optimization)

所以,我得到了这个代码:

    t = PrettyTable(['first', 'second'])
    if condition:
        for i in data_set[::-1]:
            t.add_row([i['first'], i['second'])
            # ... (multiple other commands)
    else:
        for i in data_set:
            t.add_row([i['first'], i['second'])
            # ... (same multiple commands as above)

而且我想缩短代码,这样我只需编写一次命令。这可能吗?

只需使用条件获取正确的可迭代对象,然后执行您的操作

items = data_set if condition else data_set[::-1]

for i in items:
    t.add_row([i['first'], i['second'])