Appending to a nested list

我的未来我决定 提交于 2019-12-02 10:51:37

Make a temporary list, row. Append the items from the inner loop to row, and then in the outer loop, append the row to gridList:

gridList = []
for nlist in Neighbors_List:
    row = []
    for item in nlist:
       row.append(int(FID_GC_dict[item]))
    gridList.append(row)

Note that you could also use a list comprehension here:

gridList = [[int(FID_GC_dict[item]) for item in nlist] 
            for nlist in Neighbors_List]

PS. It is best not to name a variable list, since it shadows the builtin type of the same name.

Jeff

You're appending to a single list. Try this

gridList = []
for list in Neighbors_List:
    temp = []
    for item in list:
       #print FID_GC_dict[item]
       temp.append(int(FID_GC_dict[item]))
    gridList.append(temp)
gridList = [int(FID_GC_dict[item]) for item in l for l in Neighbors_List]

Python's list comprehensions are awesome. Learn them, love them. (note this returns a list of tuples, if you want a list of lists, you can nest comprehensions.

Also, do not use list as a variable name, as it conflicts with the builtin list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!