1

複数のキーによって別の関数でクエリを実行する必要があるデータを python で集計するには、次の方法が適しているかどうか、または SQLite を使用してデータを読み書きするパフォーマンスが向上するかどうか疑問に思っています。

たとえば、集計する関数の擬似コード:

import sys

def aggregatesources(sys.argv[1],sys.argv[2],sys.argv[3]):
    source1 = open(sys.argv[1], 'r') #source1.txt
        source1data = source1.read()
    source2 = open(sys.argv[2], 'r') #source2.txt
        source1data = source2.read()
    source3 = open(sys.argv[3], 'r') #source3.txt
        source1data = source3.read()

    aggregated_data = source1 + source2 + source3 # + etc...

これは、ソースの集約を作成する必要がある関数ですが、私の質問は、ソースを次のように提供する場合です。

type1, 32
type2, 9
type3, 12
type4, 21
etc...

集約されたデータを取得し、それをより大きな辞書内で関連付けて、次のようにする方法はありますか?

type1, [source1, 32], [source2,etc...], [etc...]

これを瞬時に行うためにPythonの辞書クエリ速度を使用したいのですが、同じことを実行できる代替ソリューションがある場合は、それらについて詳しく説明してください。

4

1 に答える 1

0

これはあなたが探していることをするはずです:

import csv

def add_source_to_dict(mydict, sourcefilename):
  with open(sourcefilename, 'rb') as csvfile:
    my_reader = csv.reader(csvfile)
    for atype, value in my_reader:
      if not atype in mydict:
        mydict[atype]={}
      mydict[atype][sourcefilename] = value
  return mydict

data = {}

data = add_source_to_dict(data, "source1.txt")

インタラクティブに:

>>> data = {}
>>> data = add_source_to_dict(data, "source1.txt")
>>> data = add_source_to_dict(data, "source2.txt")
>>> data
{
  'type1,': {
    'source2.txt': '44', 
    'source1.txt': '32'
  }, 
  'type3,': {
    'source2.txt': '46', 
    'source1.txt': '12'
  }, 
  'type2,': {
    'source2.txt': '45', 
    'source1.txt': '9'
  }, 
  'type4,': {
    'source2.txt': '47', 
    'source1.txt': '21'
  }
}
于 2013-03-26T23:56:43.060 に答える