繁体   English   中英

有没有更简单的方法来检查列表的长度并输出正确的if语句?

[英]Is there a simpler way check the length of a list and output the correct if statement?

列表中变量的数量会有所不同,因此可以增加或减少,我想根据列表中变量的数量将列表中的变量转换为字符串。 我知道在此示例中,我提供了它们是字符串,但是在我的代码中,列表中的变量不是字符串。 在下面,我使用if,elif语句来转换适当数量的变量,但是有没有更简单的方法来编写呢?

列表中的变量在这里定义

a = 'apple'
b = 'banana'
c = 'cat'
d = 'dog'
e = 'eat'
f = 'fart'
g = 'game'

创建列表并将列表的长度分配给x

list_1 = [a, b, c, d, e, f, g]
x = len(list_1)

if,elif语句检查列表的长度,然后将变量转换为字符串。 这是我要简化或以更有效的方式编写的内容。

    if x == 1:
    a_new = (str(list_1[0]))
elif x == 2:
    a_new = (str(list_1[0]))
    b_new = (str(list_1[2]))
elif x == 3:
    a_new = (str(list_1[0]))
    b_new = (str(list_1[1]))
    c_new = (str(list_1[2]))
elif x == 4:
    a_new = (str(list_1[0]))
    b_new = (str(list_1[1]))
    c_new = (str(list_1[2]))
    d_new = (str(list_1[3]))
elif x == 5:
    a_new = (str(list_1[0]))
    b_new = (str(list_1[1]))
    c_new = (str(list_1[2]))
    d_new = (str(list_1[3]))
    e_new = (str(list_1[4]))
elif x == 6:
    a_new = (str(list_1[0]))
    b_new = (str(list_1[1]))
    c_new = (str(list_1[2]))
    d_new = (str(list_1[3]))
    e_new = (str(list_1[4]))
    f_new = (str(list_1[5]))
else:
    a_new = (str(list_1[0]))
    b_new = (str(list_1[1]))
    c_new = (str(list_1[2]))
    d_new = (str(list_1[3]))
    e_new = (str(list_1[4]))
    f_new = (str(list_1[5]))
    g_new = (str(list_1[6]))

我怀疑您不需要str转换(至少在您的示例中不需要)。 否则,您可以使用:

list_1 = [str(x) for x in list_1]

对于其他部分,您可以使用star *[1, 2]语法和多重赋值a, b = 1, 2

if x == 1:
    a_new = *list_1
elif x == 2:
    a_new, b_new = *list_1
elif x == 3:
    a_new, b_new, c_new = *list_1

虽然您可能只考虑使用字典

{'a_new': a, 'b_new': b}

暂无
暂无

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

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