簡體   English   中英

使用python將csv文件轉換為元組列表

[英]Converting a csv file into a list of tuples with python

我將采用4列的csv:品牌,價格,重量和類型。

類型有橙色,蘋果,梨,李子。

參數:我需要選擇最可能的重量,但是選擇1個橙子,2個梨子,3個蘋果和1個李子,不超過20美元的預算。 我不能重復相同水果的品牌(比如選擇同一品牌的蘋果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"])

你可以考慮一下:

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')]
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)

暫無
暫無

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

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