我正在使用嵌套列表在我创建的字典中查找值。然后我想将找到的值附加到列表中。我不知道如何编码的问题是如何将值保存在同一嵌套列表结构中?这是我将值附加到空列表的最后一行的代码。
#Creating a dictionary of FID: LU_Codes from external txt file
import sys, arcpy, string, csv
text_file = open("H:\SWAT\NC\FID_Whole.txt", "r")
Lines = text_file.readlines()
text_file.close()
FID_LU = map(string.split, Lines)
#print FID_LU
FID_GC_dict = dict(FID_LU)
Neighbors_file = open("H:\SWAT\NC\Sh_Neighbors2.txt","r")
Entries = Neighbors_file.readlines()
Neighbors_file.close()
Neighbors_List = map(string.split, Entries)
print Neighbors_List
#FID = [x[0] for x in Neighbors_List]
#print FID
gridList = []
for list in Neighbors_List:
for item in list:
#print FID_GC_dict[item]
gridList.append(int(FID_GC_dict[item]))
print gridList
这是邻居列表的输出(正确):
[['0', '1', '11', '12', '13'], ['1', '0', '2', '12', '13', '14'], ['2', '1', '3', '13', '14', '15'], ['3', '2', '4', '14', '15', '16'], ['4', '3', '5', '15', '16', '17'], ['5', '4', '6', '16', '17', '18'], ['6', '5', '7', '17', '18', '19'], ['7', '6', '8', '18', '19', '20'], ['8', '7', '9', '19', '20', '21'], ['9', '8', '20', '21', '22'], ['10', '11']]
这是gridList的输出(不正确):
[3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 3, 3, 3, 4, 4, 2, 3, 3, 3, 4, 2, 2, 3, 3, 3, 2, 2, 2, 3, 3, 3, 2, 2, 3, 3, 3, 3, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4]
我希望gridList看起来像是:
[[3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 2], [3, 3, 3, 4, 2, 2], [3, 3, 3, 2, 2, 2], [3, 3, 3, 2, 2, 3], [3, 3, 3, 2, 3, 3], [3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3, 3], [3, 3, 3, 3, 3], [3, 4]]
任何帮助将不胜感激。我是python的新手...阅读帖子有帮助,但我正在努力解决这个问题。
谢谢!
答案 0 :(得分:3)
制作临时列表row
。将内部循环中的项目附加到row
,然后在外部循环中将行追加到gridList
:
gridList = []
for nlist in Neighbors_List:
row = []
for item in nlist:
row.append(int(FID_GC_dict[item]))
gridList.append(row)
请注意,您也可以在此处使用list comprehension:
gridList = [[int(FID_GC_dict[item]) for item in nlist]
for nlist in Neighbors_List]
PS。最好不要命名变量list
,因为它会隐藏同名的内置类型。
答案 1 :(得分:1)
您要附加到单个列表中。试试这个
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)
答案 2 :(得分:0)
gridList = [int(FID_GC_dict[item]) for item in l for l in Neighbors_List]
Python的list comprehensions非常棒。学习他们,爱他们。 (注意这会返回一个元组列表,如果你想要一个列表列表,你可以嵌套理解。
另外,请勿将list
用作变量名称,因为它与内置list冲突
答案 3 :(得分:0)
使用一个列表:
_list = []; outer_len = 5; inner_len = 10
for outer_idx in range(outer_len):
_list.append([])
for inner_idx in range(inner_len):
_list[outer_idx].append(#stuff)