python - python 将列表拆分为嵌套列表

标签 python nested-lists

我编写了一段代码,从文件中获取字符串并将其拆分为列表。但我需要将字符串拆分为嵌套的列表。

 ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

 ['Acer', 'Beko', 'Cemex', 'Datsun', 'Equifax', 'Gerdau', 'Haribo']

这是输出,我试图弄清楚如何从第一个列表中获取数字数据并将其附加到名称列表中,以便创建下面的嵌套返回列表。任何想法都会很棒

[['Acer' 481242.74], ['Beko' 966071.86], ['Cemex' 187242.16], ['Datsun' 748502.91], ['Equifax' 146517.59], ['Gerdau' 898579.89], ['Haribo' 265333.85]]

最佳答案

使用列表理解:

the_list = ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

final_list = [[x.split()[0], float(x.split()[1])] for x in the_list]

print final_list

没有列表理解:

the_list = ['Acer 481242.74\n', 'Beko 966071.86\n', 'Cemex 187242.16\n', 'Datsun 748502.91\n', 'Equifax 146517.59\n', 'Gerdau 898579.89\n', 'Haribo 265333.85\n']

final_list = list()

for item in the_list:
    name = item.split()[0]
    amount = float(item.split()[1])
    final_list.append([name, amount])

print final_list

输出:

[['Acer', 481242.74], ['Beko', 966071.86], ['Cemex', 187242.16], ['Datsun', 748502.91], ['Equifax', 146517.59], ['Gerdau', 898579.89], ['Haribo', 265333.85]]

关于python - python 将列表拆分为嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33469880/

相关文章:

python - 如何按\n 拆分嵌套列表但跳过第一个? Python

C# 嵌套列表条目问题

python - 如何使用 Python 3.6 遍历图像文件夹并在 Jupyter Notebook 中内联打印图像

python - 向 asyncio Transport 添加方法

python - Pandas Dataframe 用其他列的第一个值填充列

python - python 中的 JSON 生成和验证库

python - 仅用于列表列表中第二项的循环。 (Python)

python - 根据第二个 df 替换 python pandas 列中的值

javascript - Angularjs Protractor : Valid Selector for excluding nested elements

python - Pandas 数据框单元格中的嵌套列表,如何提取?