gpt4 book ai didi

python - 需要使用输入将 Excel 文件中同一行中的值相乘

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:37 26 4
gpt4 key购买 nike

import csv

file_reader = csv.DictReader(open('FILENAME.CSV','r'))

for row in file_reader:

print(row)

animal_input=input("What kind of animal?")

print("To buy all those animals costs:"PRICE*QUANTITY)

我需要能够在 input() 中输入动物的名称,以便显示价格 X 数量。但是,该数据表位于Excel文件内部,因此我不知道如何从input()引用Excel文件中的“ANIMAL”列,也不知道如何包含价格以及数量。

ANIMAL         PRICE   QUANTITY
ANTEATER 5 4
BEAR 3 4
CAT 3 4
DOG 2 3
ECHIDNA 2 2

最佳答案

也许使用字典,并计算阅读结果。

import csv
import StringIO

csv_pretend_file = """ANIMAL,PRICE,QUANTITY
ANTEATER,5,4
BEAR,3,4
CAT,3,4
DOG,2,3
ECHIDNA,2,2"""

animals = {}

for row in csv.DictReader(StringIO(csv_pretend_file)):
animals[row['ANIMAL']] = int(row['PRICE']) * int(row['QUANTITY'])


animal_input=input("What kind of animal?")
print("To buy all those animals costs: {}".format(animals[animal_input]))

演示:

What kind of animal?ANTEATER


To buy all those animals costs: 20

关于python - 需要使用输入将 Excel 文件中同一行中的值相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46189034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com