首页 > 解决方案 > 如何通过列逐行遍历表并将其放入Python中的列表中

问题描述

列表1

0, 19.2, 20.3, 21.3, 23.5, 24.6, 25.2, 25.4, 26.2, 26.3, 26.4, 8655, Light
26.2, 25.7, 25.2, 25.3, 22.3, 21.2, 20, 19.2, 19.1, 0, 0, 8655 , Light
0, 0, 54.2, 56.3, 62.3, 63.3, 65.2, 65.3, 65.3, 65.4, 65.4, 8483, Fan
65.4, 65.2, 65.1, 64.2, 63.2, 62.5, 61.3, 56.4, 53.8, 53.2, 0, 8483, Fan
32.3, 33.6, 34.2, 36.3, 34.1, 32.3, 33.6, 33.5, 33.2, 33.3, 33.3, 8470, Fridge
32.3, 34.6, 35.2, 36.3, 34.1, 32.1, 33.6, 33.3, 33.2, 33.3, 33.3, 8470, Fridge
0, 129.3, 2235.6, 2236.2, 2235.5, 2232.3, 2235.6, 2234.2, 2235.2, 2235.4, 2235.6, 8903, WaterHeater
2236.4, 2235.2, 2235.6, 2236.2, 2235.5, 2232.3, 2235.6, 2234.2, 1992.5, 119.3, 0, 8903, WaterHeater

问题:如何编写程序以便逐行遍历列表并附加到列表中(将用于 K 最近邻预测)

列表:[0, 19.2, 20.3, 21.3, 23.5, 24.6, 25.2, 25.4, 26.2, 26.3, 26.4, 8655, 光]

Such that it will be in a list after convert to 2D Array 
List:[[0],
     [19.2],
     [20.3],
     [21.3],
     [26.4],
     [Light]]

标签: pythonmachine-learning

解决方案


You can use the below code.

l = [0, 19.2, 20.3, 21.3, 23.5, 24.6, 25.2, 25.4, 26.2, 26.3, 26.4, 8655, 'Light']

final_list=[]
for i in l:
    final_list.append([i])

If you want to iterate through a table which I'm presuming to be a list of lists, then use the below code.

l1 = [0, 19.2, 20.3, 21.3, 23.5, 24.6, 25.2, 25.4, 26.2, 26.3, 26.4, 8655, 'Light']
[26.2, 25.7, 25.2, 25.3, 22.3, 21.2, 20, 19.2, 19.1, 0, 0, 8655 , 'Light']
[0, 0, 54.2, 56.3, 62.3, 63.3, 65.2, 65.3, 65.3, 65.4, 65.4, 8483, 'Fan']
[65.4, 65.2, 65.1, 64.2, 63.2, 62.5, 61.3, 56.4, 53.8, 53.2, 0, 8483, 'Fan']
[32.3, 33.6, 34.2, 36.3, 34.1, 32.3, 33.6, 33.5, 33.2, 33.3, 33.3, 8470, 'Fridge']
[32.3, 34.6, 35.2, 36.3, 34.1, 32.1, 33.6, 33.3, 33.2, 33.3, 33.3, 8470, 'Fridge']
[0, 129.3, 2235.6, 2236.2, 2235.5, 2232.3, 2235.6, 2234.2, 2235.2, 2235.4, 2235.6, 8903, 'WaterHeater']
[2236.4, 2235.2, 2235.6, 2236.2, 2235.5, 2232.3, 2235.6, 2234.2, 1992.5, 119.3, 0, 8903, 'WaterHeater']

final_list=[]

for l in l1:
    for i in l:
        final_list.append([i])

You will have your result in final_list.


推荐阅读