我是python的新手,我需要从字符串列表中创建一个浮点值列表(矩阵)列表。所以,如果我的输入是:
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"]
我想要获得的是:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 0, 7], [5, 4, 3, 2], [2, 3, 3, 3], [2, 2, 3, 3]]
这是我的代码:
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]]
错误在哪里?我找不到它。感谢
答案 0 :(得分: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]]
答案 1 :(得分: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]]