Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中存储.csv数据_Python_List_Csv - Fatal编程技术网

在Python中存储.csv数据

在Python中存储.csv数据,python,list,csv,Python,List,Csv,我有两个变量–动物和食物;如果我把它们打印出来 var1 var2 pig acorn pig acorn pig carrot pig potato pig acorn pig carrot dog meat dog acorn dog carrot dog potato dog carrot dog meat cat meat cat fish cat carrot cat potato 等等 我希望此数据以以下格式存储在新的CSV文件中(但不知道如何执行此

我有两个变量–
动物
食物
;如果我把它们打印出来

var1 var2
pig  acorn
pig  acorn
pig  carrot
pig  potato
pig  acorn
pig  carrot
dog  meat
dog  acorn
dog  carrot
dog  potato
dog  carrot
dog  meat
cat  meat
cat  fish
cat  carrot
cat  potato
等等

我希望此数据以以下格式存储在新的CSV文件中(但不知道如何执行此操作):

等等。。。 换句话说,我希望
动物
变量中的观察重复出现的次数与
食物
变量中不同类型的项目重复出现的次数相同,并将聚合分数放入一个新变量中。例如,如果出现了50次
,其中30次是
橡子
,10次是
胡萝卜
,10次是
土豆
,我希望它看起来像这样:

pig acorn  30
pig carrot 10
pig potato 10

首先,这与CSV本身没有什么关系。如果你想像这里这样计算数值,使用字典是个好主意,所以你需要的是这样的东西(我假设动物和食物是列表):

在这个循环之后,您将拥有一个字典,其中的键是(动物、食物)元组,值是计数。因此,您可以将它们写入csv,如:

for ((animal, food), count) in counts.items():
    csv_writer.writerow([animal, food, count])

看起来您不知道
集合的奇妙
计数器
。这是你的电话号码

如果要计算变量对,请执行以下操作:

c = Counter(zip(var1, var2))
要编写结果,请使用zetciu答案中报告的
csv
库,但请记住计数器实例是
dict

with open('result.csv', 'wb') as csvfile:
    csv_writer = csv.writer(csvfile)
    csv_writer.writerow(["animals", "food", "count"])
    for pair,count in c.items():
         animal, food = pair
         csv_writer.writerow([animal, food, count])

动物
食物
是列表吗?不是,但我想将它们存储为列表。或者更确切地说,作为字典,
动物
食物
是如何表示的?你说它们是Python变量。我的坏,它们是列表。还要考虑,优化计数应用程序。
c = Counter(zip(var1, var2))
with open('result.csv', 'wb') as csvfile:
    csv_writer = csv.writer(csvfile)
    csv_writer.writerow(["animals", "food", "count"])
    for pair,count in c.items():
         animal, food = pair
         csv_writer.writerow([animal, food, count])