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

时间:2018-10-11 15:39:51

标签: python

列表中的变量数量会有所不同,因此可以增加或减少,我想根据列表中变量的数量将列表中的变量转换为字符串。我知道在此示例中,我提供了它们是字符串,但是在我的代码中,列表中的变量不是字符串。在下面,我使用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]))

1 个答案:

答案 0 :(得分:0)

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

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

对于另一部分,您可以使用星形*[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}