1

I'm new to python and I need to create a list of lists (a matrix) of float values from a list of strings. So if my input is:

objectListData = ["1, 2, 3, 4", "5, 6, 7, 8", "9, 0, 0, 7", "5, 4, 3, 2", "2, 3, 3, 3", "2, 2, 3, 3"]

what I want to obtain is:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 7], [5, 4, 3, 2], [2, 3, 3, 3], [2, 2, 3, 3]]

Here's my code:

objectListData = ["1, 2, 3, 4", "5, 6, 7, 8", "9, 0, 0, 7", "5, 4, 3, 2", "2, 3, 3, 3", "2, 2, 3, 3"]


objectListDataFloats = [[0] * len(objectListData[0].split(', '))] * len(objectListData)
for count in range(1,len(objectListData)):
    for ii in range(1,len(objectListData[count].split(', '))):
        objectListDataFloats[count][ii] = float(objectListData[count].split(', ')[ii])

print objectListDataFloats

objectListDataFloats=[[0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0], [0, 2.0, 3.0, 3.0]]

where is the error? I can't find it. Thanks

4

2 回答 2

4

给你:

[[int(y) for y in x.split(",")] for x in objectListData]

输出:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 7], [5, 4, 3, 2], [2, 3, 3, 3], [2, 2, 3, 3]]

或者,如果你想要浮动:

[[float(y) for y in x.split(",")] for x in objectListData]

输出:

[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 0.0, 0.0, 7.0], [5.0, 4.0, 3.0, 2.0], [2.0, 3.0, 3.0, 3.0], [2.0, 2.0, 3.0, 3.0]]
于 2013-08-09T18:23:38.297 回答
2

问题是您的内部列表是对单个列表的引用,而不是单个列表。

>>> objectListDataFloats = [[0] * len(objectListData[0].split(', '))] * len(objectListData)

>>> objectListDataFloats
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> id(objectListDataFloats[0]) == id(objectListDataFloats[1])
True

修复该问题后,您需要从 的起始索引进行迭代0,因为 Python 中的列表从 0 开始索引。

for count in range(len(objectListData)):
    for ii in range(len(objectListData[count].split(', '))):
        objectListDataFloats[count][ii] = float(objectListData[count].split(', ')[ii])


>>> objectListDataFloats
[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 0.0, 0.0, 7.0], [5.0, 4.0, 3.0, 2.0], [2.0, 3.0, 3.0, 3.0], [2.0, 2.0, 3.0, 3.0]]

要完全取消使用零的列表的初始初始化,您也可以在进行时构建列表,例如

>>> objectListDataFloats = []
>>> for elem in objectListData:
        test_list = []
        for val in elem.split(','):
            test_list.append(float(val))
        objectListDataFloats.append(test_list)


>>> objectListDataFloats
[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 0.0, 0.0, 7.0], [5.0, 4.0, 3.0, 2.0], [2.0, 3.0, 3.0, 3.0], [2.0, 2.0, 3.0, 3.0]]

您不需要使用索引来遍历列表或字符串,您可以像上面的示例一样遍历列表。

减少解决方案-

您可以将整个解决方案简化为以下内容(如果您需要浮点数,请更改int为)float

>>> objectListData = ["1, 2, 3, 4", "5, 6, 7, 8", "9, 0, 0, 7", "5, 4, 3, 2", "2, 3, 3, 3", "2, 2, 3, 3"]
>>> [map(int, elem.split(',')) for elem in objectListData]
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 7], [5, 4, 3, 2], [2, 3, 3, 3], [2, 2, 3, 3]]
于 2013-08-09T18:22:21.633 回答