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



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

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

最新更新