web-dev-qa-db-ja.com

pythonを使用してcsvファイルをタプルのリストに変換する

私は、ブランド、価格、重量、タイプの4つの列を持つcsvを使用します。

タイプはオレンジ、アップル、ナシ、プラムです。

パラメータ:可能な限りの重量を選択する必要がありますが、予算が20ドルを超えないようにして、オレンジ1つ、梨2つ、リンゴ3つ、梅1つを選択します。同じ果物のブランドを繰り返すことはできません(同じブランドをApple 3回など)選択するなど)。

Pythonでcsvファイルを開いて読み取ることはできますが、csvファイルからタプルの辞書またはリストを作成する方法がわかりません。

より明確にするために、ここにデータのアイデアがあります。

Brand, Price, Weight, Type
brand1, 6.05, 3.2, orange
brand2, 8.05, 5.2, orange
brand3, 6.54, 4.2, orange
brand1, 6.05, 3.2, pear
brand2, 7.05, 3.6, pear
brand3, 7.45, 3.9, pear
brand1, 5.45, 2.7, Apple
brand2, 6.05, 3.2, Apple
brand3, 6.43, 3.5, Apple
brand4, 7.05, 3.9, Apple
brand1, 8.05, 4.2, Plum
brand2, 3.05, 2.2, Plum

ここに私が今持っているすべてがあります:

import csv
test_file = 'testallpos.csv'
csv_file = csv.DictReader(open(test_file, 'rb'), ["brand"], ["price"], ["weight"], ["type"])
15
Sean

あなたはこれを熟考することができます:

import csv

def fitem(item):
    item=item.strip()
    try:
        item=float(item)
    except ValueError:
        pass
    return item        

with open('/tmp/test.csv', 'r') as csvin:
    reader=csv.DictReader(csvin)
    data={k.strip():[fitem(v)] for k,v in reader.next().items()}
    for line in reader:
        for k,v in line.items():
            k=k.strip()
            data[k].append(fitem(v))

print data 

プリント:

{'Price': [6.05, 8.05, 6.54, 6.05, 7.05, 7.45, 5.45, 6.05, 6.43, 7.05, 8.05, 3.05],
 'Type': ['orange', 'orange', 'orange', 'pear', 'pear', 'pear', 'Apple', 'Apple', 'Apple', 'Apple', 'Plum', 'Plum'], 
 'Brand': ['brand1', 'brand2', 'brand3', 'brand1', 'brand2', 'brand3', 'brand1', 'brand2', 'brand3', 'brand4', 'brand1', 'brand2'], 
 'Weight': [3.2, 5.2, 4.2, 3.2, 3.6, 3.9, 2.7, 3.2, 3.5, 3.9, 4.2, 2.2]}

行ごとのタプルとしてcsvファイルが必要な場合:

import csv
with open('/tmp/test.csv') as f:
    data=[Tuple(line) for line in csv.reader(f)]

print data
# [('Brand', ' Price', ' Weight', ' Type'), ('brand1', ' 6.05', ' 3.2', ' orange'), ('brand2', ' 8.05', ' 5.2', ' orange'), ('brand3', ' 6.54', ' 4.2', ' orange'), ('brand1', ' 6.05', ' 3.2', ' pear'), ('brand2', ' 7.05', ' 3.6', ' pear'), ('brand3', ' 7.45', ' 3.9', ' pear'), ('brand1', ' 5.45', ' 2.7', ' Apple'), ('brand2', ' 6.05', ' 3.2', ' Apple'), ('brand3', ' 6.43', ' 3.5', ' Apple'), ('brand4', ' 7.05', ' 3.9', ' Apple'), ('brand1', ' 8.05', ' 4.2', ' Plum'), ('brand2', ' 3.05', ' 2.2', ' Plum')]
20
dawg
_import csv
with open("some.csv") as f:
       r = csv.reader(f)
       print filter(None,r)
_

またはリスト内包表記

_import csv
with open("some.csv") as f:
       r = csv.reader(f)
       print [row for row in r if row]
_

比較のために

_In [3]: N = 100000

In [4]: the_list = [randint(0,3) for _ in range(N)]

In [5]: %timeit filter(None,the_list)
1000 loops, best of 3: 1.91 ms per loop

In [6]: %timeit [i for i in the_list if i]
100 loops, best of 3: 4.01 ms per loop
_

[編集]実際の出力には空白がないので、リスト内包表記やフィルターは必要ありませんlist(r)

空白行のない最終回答

_import csv
with open("some.csv") as f:
       print list(csv.reader(f))
_

あなたが辞書を使いたいなら、あなたはできる

_import csv
with open("some.csv") as f:
       reader = list(csv.reader(f))
       print [dict(Zip(reader[0],x)) for x in reader]
       #or
       print map(lambda x:dict(Zip(reader[0],x)), reader)
_
1
Joran Beasley