1

Python 2.7を使用して、特定のセルの値をどのように変更しますか?データベースを作成するのが最善の方法ですか?(「1ダース」を2回12に変更-「1ダース」が見つかるたびに12に置き換えられます)

入力:

['item', 'amount', 'size', 'price']
['apple', '1 dozen', '3', '8']
['cherry', '84', '100 g', '3.5']
['orange', '1 dozen', '3', '9']

必要な出力:

['item', 'amount', 'size', 'price']
['apple', '12', '3', '8']
['cherry', '84', '100 g', '3.5']
['orange', '12', '3', '9']
4

1 に答える 1

0

入力が file にあると仮定するamounts.csvと、次のことを試すことができます。

import csv

# Keep a dictionary of the changes you want to make
changes = {
    '1 dozen': 12
    }

with open('amounts.csv', 'rb') as f:
    reader = csv.reader(f)

    # Iterating through the list of lists
    for row in reader:
        # Look up each value in your dictionary and return the
        # corresponding 'changes' value if it finds a match.
        # If a match isn't found, just return the item itself.
        print [changes.get(item, item) for item in row]

どちらが出力されますか:

['item', 'amount', 'size', 'price']
['apple', 12, '3', '8']
['cherry', '84', '100 g', '3.5']
['orange', 12, '3', '9']

printここでは出力を表示するだけでした-ユースケースに合わせて調整できます。

于 2013-01-13T22:40:03.647 に答える