拆分包含字符串的列表的列表

时间:2019-02-27 08:53:23

标签: python list

我有一个这样的列表列表:

[["testo=text1","testo2=text2"],["testo3=text3","testo4=text4"]]

我想用"="分割每个子列表的每个元素。

所需结果:

[['testo', 'text1'],['testo2', 'text2']]

我的尝试是遍历每个子列表并拆分。但这不起作用:

[j.split("=") for j in [i for i in splitted_params]]

继续遇到'list' object has no attribute 'split'错误

4 个答案:

答案 0 :(得分:2)

尝试:

l = [["testo=text1","testo2=text2"],["testo3=text3","testo4=text4"]]

new_l = [inner_element.split("=") for x in l for inner_element in x]

print(new_l)

输出:

[['testo', 'text1'], ['testo2', 'text2'], ['testo3', 'text3'], ['testo4', 'text4']]

答案 1 :(得分:1)

您不应该对python列表理解很聪明。我认为,您应该寻求可读的解决方案。 :)

if __name__ == '__main__':
    data = [
        ["testo=text1","testo2=text2"],
        ["testo3=text3","testo4=text4"]
    ]

    for arr in data:
        for index in range( len(arr) ):
            arr[index] = arr[index].split('=')

    print(data)

在表达式[j.split("=") for j in [i for i in splitted_params]]中,首先对内部表达式[i for i in splitted_params]求值,这将为您提供一个列表。您在此列表理解中没有执行任何操作。然后,当您评估[j.split("=") for j in SOME_RESULT_YOU_GOT]时,您试图拆分列表,这是不可能的。

答案 2 :(得分:1)

您可以使用chain.from_iterable()来避免列表理解中的双重for循环:

from itertools import chain

l = [["testo=text1", "testo2=text2"], ["testo3=text3", "testo4=text4"]]

[i.split('=') for i in chain.from_iterable(l)]
# [['testo', 'text1'], ['testo2', 'text2'], ['testo3', 'text3'], ['testo4', 'text4']]

说明您的解决方案不起作用的原因:

splitted_params = [["testo=text1", "testo2=text2"], ["testo3=text3", "testo4=text4"]]

print([i for i in splitted_params] == splitted_params)
# True

因此,当您在listcomp中使用[i for i in splitted_params]时,您将获得相同的列表。

答案 3 :(得分:0)

我认为问题是[i for i in splitted_params]不会返回列表列表中的列表。 它只是返回列表列表,因此当您再次循环浏览它时,它将尝试在列表列表中拆分列表。

所以我建议您在这样的循环中做一个循环

listoflists = [["testo=text1", "testo2=text2"], ["testo3=text3", "testo4=text4"]]
for i in listoflists:
    for j in i:
        print(j.split("="))

它可能不那么漂亮,但是确实可以完成工作。