python - 在一条记录中连接多个值而不重复

标签 python vba

我有一个如下所示的 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 moduledefaultdict 大大简化了代码:

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/

相关文章:

python 如何检查数据帧中的值是否为nan

python - SciPy firwin2 设计任意幅度滤波器时频率误差较低

excel - 范围内的替代行颜色

python - 交叉连接两个 vector 的元素以产生第三个 vector

python - 用表中的单个 unicode 替换字母数字子字符串

excel - 如何引用父类终止一个类?

excel - 使用VBA获取MDX数据

xml - 如何将多个 XML 中的值提取到 Excel 中?

vba - 如何从 Excel VBA 中的某个范围获取唯一值的列表?

Python2 和 Python3 : __init__ and __new__