python组多个相似if语句

2024-06-07 22:55:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将大量类似的if-else语句或类似于以下良好实践的写作进行分组

if len(G72List) > 1 and G72List[1] != "":
    G7201Value = G72List[1]
else:
    G7201Value = ""

if len(G72List) > 5 and G72List[5] != "":
    G7205Value = G72List[5]
else:
    G7205Value = ""

if len(G72List) > 6 and G72List[6] != "":
    G7206Value = G72List[6]
else:
    G7206Value = ""

if len(G72List) > 7 and G72List[7] != "":
    G7207Value = G72List[7]
else:
    G7207Value = ""

if len(G72List) > 8 and G72List[8] != "":
    G7208Value = G72List[8]
else:
    G7208Value = ""

if len(G72List) > 9 and G72List[9] != "":
    G7209Value = G72List[9]
else:
    G7209Value = ""

if len(G72List) > 10 and G72List[10] != "":
    G7210Value = G72List[10]
else:
    G7210Value = ""

Tags: andlenif语句elseg72listg7207valueg7206value
2条回答

我找到了这种方法来演示您可以做什么:

from contextlib import suppress


G7201Value = G7205Value = G7206Value = G7207Value = G7209Value = G7210Value = 'empty'


for i in range(12):
    G72List = [_ for _ in range(i)]
    print(G72List)
    
    with suppress(IndexError):
        G7201Value = G72List[1]
        G7205Value = G72List[5]
        G7206Value = G72List[6]
        G7207Value = G72List[7]
        G7208Value = G72List[8]
        G7209Value = G72List[9]
        G7210Value = G72List[10]


    print(
        G7201Value,
        G7205Value,
        G7206Value,
        G7207Value,
        G7209Value,
        G7210Value
     )

输出:

$ python3 g27.py 
[]
empty empty empty empty empty empty
[0]
empty empty empty empty empty empty
[0, 1]
1 empty empty empty empty empty
[0, 1, 2]
1 empty empty empty empty empty
[0, 1, 2, 3]
1 empty empty empty empty empty
[0, 1, 2, 3, 4]
1 empty empty empty empty empty
[0, 1, 2, 3, 4, 5]
1 5 empty empty empty empty
[0, 1, 2, 3, 4, 5, 6]
1 5 6 empty empty empty
[0, 1, 2, 3, 4, 5, 6, 7]
1 5 6 7 empty empty
[0, 1, 2, 3, 4, 5, 6, 7, 8]
1 5 6 7 empty empty
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1 5 6 7 9 empty
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1 5 6 7 9 10

简单但有效;-)

让我解释一下:

您可以在其中尝试查看列表是否足够长,然后检查要从中提取的索引处的值是否有值,然后分配该值,或者将该值设置为""。不需要这样做,只需使用空字符串一次初始化所有变量即可。 After,使用contextlib.suppress(IndexError),只要不引发IndexError,就允许在suppress之后缩进的代码段继续进行;-)

免责声明:

for i in range(12):
    G72List = [_ for _ in range(i)]
    print(G72List)

只是为了演示的目的,向您展示各种长度的行为列表

一系列只因数字不同的变量名可以重构为dict(如果从0开始,递增1,则可能是一个列表)。然后重复可以分解成for循环

GValue = {}
for i in [1, *range(5, 11)]:
    if len(G72List) > i and G72List[i] != "":
        GValue[7200+i] = G72List[i]
    else:
        GValue[7200+i] = ""

相关问题 更多 >

    热门问题