簡體   English   中英

讀取 CSV 文件並附加到字典

[英]Read a CSV file and Append to dictionary

請問如何遍歷csv文件RESULT4中的所有行,然后檢查元組列表BR以查看每個元組中的第一個和第二個元素是否分別與NodeA和NodeB列中的值匹配並添加相應的值如果它們匹配,則在 LOAD 列中放入 BR 中的字典元素。 謝謝

RESULT4.csv = Link  NodeA   NodeB   LOAD
               4    71001   8427    961.325492
               6    71002   71009   17.302306
              12    71004   8430    0.642499
              15    71003   8429    3.685375
              16    71006   8833    1.291624
              18    71007   71008   6.536354
              20    71009   70514   65.200511


BR = [(71001, 8427,{'lanes': 9, 'length': 0.1,}),(71003, 8429,{'lanes': 9, 'length': 0.8,}),(71007, 71008,{'lanes': 6, 'length': 0.3,}), (7100, 7104,{'lanes': 6, 'length': 0.3,})]

我試過這個,但我沒有得到想要的結果。

with open('RESULT4.csv', 'rb') as f:
    reader = csv.reader(f)
        for row in reader:
            if (BR[0][0]).find(row[1]) and (BR[0][1]).find(row[2]):
            BR[0][2]['volume'] = str(row[3])
print BR

輸出應該是這樣的:

BR = [(71001, 8427,{'volume': 961.325492, 'lanes': 9, 'length': 0.1,}),(71003, 8429,{'volume': 3.685375,'lanes': 9, 'length': 0.8,}),(71007, 71008,{'volume': 6.536354,'lanes': 6, 'length': 0.3,}), (7100, 7104,{'lanes': 6, 'length': 0.3,})]

主要是您的算法失敗了,因為您省略了元組列表中的第二個循環。

使用此 csv 文件:

Link,NodeA,NodeB,LOAD
4,71001,8427,961.325492
6,71002,71009,17.302306
12,71004,8430,0.642499
15,71003,8429,3.685375
16,71006,8833,1.291624
18,71007,71008,6.536354
20,71009,70514,65.200511

和這段代碼

import csv

BR = [(71001, 8427,{'lanes': 9, 'length': 0.1,}),
        (71003, 8429,{'lanes': 9, 'length': 0.8,}),
        (71007, 71008,{'lanes': 6, 'length': 0.3,}), 
        (7100, 7104,{'lanes': 6, 'length': 0.3,})]

with open('result4.csv') as f:
        for row in csv.DictReader(f):
            for nodeA, nodeB, attrDict in BR:
                if nodeA == int(row['NodeA']) and nodeB == int(row['NodeB']):
                    attrDict.update({'volume' : str(row['LOAD'])})
print BR

我得到這個輸出:

[(71001, 8427, {'volume': '961.325492', 'length': 0.1, 'lanes': 9}), 
 (71003, 8429, {'volume': '3.685375', 'length': 0.8, 'lanes': 9}), 
 (71007, 71008, {'volume': '6.536354', 'length': 0.3, 'lanes': 6}), 
 (7100, 7104, {'length': 0.3, 'lanes': 6})]

我希望這可以幫助你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM