可能重复:
Adding a constant integer to a value in a python dictionary
这是一份报告,因为我以前不太清楚问我的问题。我正在做一个元胞自动机代码,我已经制作了一个arcgis shapefile FID和Land Use Codes的字典。 FID是点或单元ID。我还创建了每个点的相邻邻居的嵌套列表。目前,我正在通过在arcgis中进行聚类分析来寻找类似土地使用代码的集群。我为每个FID创建了一个字典,它是否是聚类的,可以是“无”或“HH”。代码将做的是为每个点提供点的相邻邻居的集群代码。如果列表中的所有值都有'HH',那么我想从FID / LandUse字典中获取土地使用代码。然后我想为gridList2中的每个土地使用代码添加一个整数1并更新FID / LandUse字典,但仅当土地使用代码在1到5之间时。所以我不会更新FID / LandUse中的每个值字典,只是与gridList2对应的字典。我编写的代码不起作用,因为当我只为一个字典键添加1时,我显然正在遍历整个gridList。
以下是代码:
import arcpy, string, csv
#Creating a dictionary of FID: LU_Codes from external txt file
text_file = open("H:\SWAT\NC\FID_Whole_Copy.txt", "rb")
FID_GC_dict = {}
reader = csv.reader(text_file, delimiter='\t')
for line in reader:
FID_GC_dict[line[0]] = int(line[1])
text_file.close()
#Importing neighbor list file for each FID value
Neighbors_file = open("H:\SWAT\NC\Pro_NL_Copy.txt","rb")
Entries = Neighbors_file.readlines()
Neighbors_file.close()
Neighbors_List = map(string.split, Entries)
#creates a list of the current FID
FID = [x[0] for x in Neighbors_List]
#print FID
Cluster_dict = {}
sc1 = arcpy.SearchCursor('H:\\SWAT\\NC\\cluster.shp')
for row in sc1:
Cluster_dict[str(row.FID)] = [row.COType]
for k, v in Cluster_dict.iteritems():
if v == [u' ']:
Cluster_dict[k] = 'None'
if v == [u'HH']:
Cluster_dict[k] = 'HH'
#print Cluster_dict
i = iter(FID)
Cur_FID = i.next()
clusterList = []
for clist in Neighbors_List:
if clist[0] == Cur_FID:
for ccodes in clist:
clusterList.append(Cluster_dict[ccodes])
print clusterList
numtot = len(clusterList)
noc = clusterList.count('HH')
diff = numtot - noc
print diff
if diff == 0:
gridList2 = []
for nlist in Neighbors_List:
if nlist[0] == Cur_FID:
for neighbors in nlist:
gridList2.append(FID_GC_dict[neighbors])
print gridList2
for lucodes in gridList2:
if lucodes > 1: #I haven't condensed these two lines of code yet.
if lucodes < 5:
FID_GC_dict[Cur_FID] = lucodes + 1 #This gives me a value of 5...should be 4, see below.
print FID_GC_dict[Cur_FID]
因此,如果第一个FID为'0',则邻居列表将为['0','1','12','13','14']。所有值都有一个'HH',所以我想从FID / Landuse字典中获取土地使用代码:[3,3,4,4,4]。然后我想将1添加到gridList2(我发现它是不可变的)并更新FID / LandUSE字典。