我有一个如下所示的 dbf 表,它是从两个表进行一对多连接的结果。我想从一个 Taxlot id 字段中获得唯一的区域值。
表名:输入表
tid ----- 区域
1 ------ 一个
1 ------ 一个
1 ------ 乙
1 ------ C
2 ------ D
2 ------ E
3 ------ C
理想的输出表
表名:输入表
tid ----- 区域
1 ------ A、B、C
2 ------ D, E
3 ------ C
我得到了一些帮助,但无法正常工作。
inputTbl = r"C:\temp\input.dbf"
taxIdZoningDict = {}
searchRows = gp.searchcursor(inputTbl)
searchRow = searchRows.next()
while searchRow:
if searchRow.TID in taxIdZoningDict:
taxIdZoningDict[searchRow.TID].add(searchRow.ZONE)
else:
taxIdZoningDict[searchRow.TID] = set() #a set prevents dulpicates!
taxIdZoningDict[searchRow.TID].add(searchRow.ZONE)
searchRow = searchRows.next()
outputTbl = r"C:\temp\output.dbf"
gp.CreateTable_management(r"C:\temp", "output.dbf")
gp.AddField_management(outputTbl, "TID", "LONG")
gp.AddField_management(outputTbl, "ZONES", "TEXT", "", "", "20")
tidList = taxIdZoningDict.keys()
tidList.sort() #sorts in ascending order
insertRows = gp.insertcursor(outputTbl)
for tid in tidList:
concatString = ""
for zone in taxIdZoningDict[tid]
concatString = concatString + zone + ","
insertRow = insertRows.newrow()
insertRow.TID = tid
insertRow.ZONES = concatString[:-1]
insertRows.insertrow(insertRow)
del insertRow
del insertRows
最佳答案
我会使用 my dbf module和 defaultdict
大大简化了代码:
import dbf
from collections import defaltdict
inputTbl = dbf.Table(r'c:\temp\input.dbf')
taxIdZoning = defaultdict(set)
for record in inputTbl:
taxIdZoning[record.tid].add(record.zone)
inputTbl.close()
outputTbl = dbf.Table(r'c:\temp\output.dbf', 'tid N(17.0), zones C(20)')
for tid in sorted(taxIdZoning):
record = outputTbl.append()
record.tid = tid
record.zones = ','.join(sorted(taxIdZoning[tid]))
outputTbl.close()
注意:字段名称是小写的,我不确定如何表示 LONG,但希望 17 位数字就足够了。 :) 对于任何错误,我深表歉意——没有输入文件很难测试。
关于python - 在一条记录中连接多个值而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2464031/