我有两个变量animals
和food
;如果我打印它们,它们看起来像
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文件中(但不知道如何执行此操作):
animals food count
pig acorn 15
pig carrot 7
pig potato 10
dog acorn 2
dog meat 10
dog potato 1
等等。。。
换言之,我希望animals
变量中的观察重复出现的次数与food
变量中不同类型的项目重复出现的次数相同,并将聚合分数放入新变量中。例如,如果出现了50次pig
,其中30次是acorn
,10次是carrot
,10次是potato
,我希望它是这样的:
pig acorn 30
pig carrot 10
pig potato 10
首先-这与CSV本身没有什么关系。如果你想像这里一样计算值,使用字典是个好主意,所以你需要的是这样的东西(我假设动物和食物是列表):
在这个循环之后,您将拥有一个字典,其中的键是(动物、食物)元组,值是计数。因此您可以将它们写入csv,如:
看起来您不知道
Counter
类的collections
。这是documentation。你知道吗如果要计算变量对:
要编写结果,请使用zetciu answer中报告的
csv
库,但请记住计数器实例是dict
。你知道吗相关问题 更多 >
编程相关推荐