Python3 csv数据结构问题

2024-06-16 12:15:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的csv文件

Category    Subcategory
-----------------------
cat         panther
cat         tiger
dog         wolf
dog         heyena
cat         lion
dog         beagle

我正在尝试编写一个脚本,输出如下内容(顺序不重要):

animals = [
              [['cat'], ['panther', 'tiger', 'lion']],
              [['dog'], ['wolf', 'heyena', 'beagle']]
          ]

到目前为止,我能够使一个独特的类别列表,和一个独特的子类别列表。你知道吗

for p in infile:
    if(p[0] not in catlist):
        catlist.append(p[0])
    if(p[1] not in subcatlist) :
        subcatlist.append(p[1])

但是我很难写出这样的逻辑:“如果‘猫’在动物中,【】,但‘豹’不在‘猫’中,就加上它。”

我玩过一些zip()和dict(),但我几乎只是在这里挥舞。对python相当陌生。使用Python3。你知道吗


Tags: in列表ifnot类别cattigerdog
2条回答

如果要将键映射到某些值,那么使用字典就容易得多。建造它们特别方便的是defaultdict。你知道吗

假设您的infile将输入行拆分为空白,那么以下内容应该会有所帮助:

from collections import defaultdict

animals = defaultdict(list)

for p in infile:
    animals[p[0]].append(p[1])

您可以考虑使用集合和dict。使用类别名称作为字典的键。所以对于每个p in infileanimals[p[0]].add(p[1]),假设p0,p1是类型和物种。你知道吗

这样做的好处是,如果“Panther”多次以“Cat”的形式出现,则不必检查它是否已存在于“Cat”列表中,因为set类型将确保您拥有一组唯一的元素。你知道吗

>>> from collections import defaultdict
>>> animals = defaultdict(set)
>>> animals['Cat'].add('Panther')
>>> animals
defaultdict(<class 'set'>, {'Cat': {'Panther'}})
>>> animals['Cat'].add('Lion')
>>> animals
defaultdict(<class 'set'>, {'Cat': {'Lion', 'Panther'}})
>>> animals['Cat'].add('Panther')
>>> animals
defaultdict(<class 'set'>, {'Cat': {'Lion', 'Panther'}})

与使用列表相比:

>>> moreanimals = defaultdict(list)
>>> moreanimals['Cat'].append('Panther')
>>> moreanimals
defaultdict(<class 'list'>, {'Cat': ['Panther']})
>>> moreanimals['Cat'].append('Panther')
>>> moreanimals
defaultdict(<class 'list'>, {'Cat': ['Panther', 'Panther']})

相关问题 更多 >