【问题标题】:Unique elements of list within list in pythonpython中列表中列表的唯一元素
【发布时间】:2013-10-20 21:23:59
【问题描述】:

我们得到了一份不同动物园里的动物名单,需要找出哪些动物园里有其他动物园里没有的动物。每个动物园的动物都是用空格隔开的,每个动物园原来是用逗号隔开的。

我目前正在枚举所有动物园以拆分每种动物并在列表中为不同的动物园创建列表:

for i, zoo in enumerate(zoos):
    zoos[i] = zoo.split()

但是,我不知道如何判断和计算有多少动物园拥有独特的动物。我认为这是 enumerate 的其他东西,可能是集合,但不能完全理解。

【问题讨论】:

  • 你能添加一些数据结构的例子吗?
  • 如果你把代码和数据展示出来,而不是仅仅描述它,效果会更好。

标签: python list set enumerate


【解决方案1】:

你应该使用集合。

一个集合只有唯一的项目,每次你想到列表中的唯一项目时,你应该想到集合。

创建一个包含特定动物园动物的集合 A,以及包含所有其他动物的集合 B。 然后迭代以删除 A 中 B 中的所有动物。 结果将是独特的例子。

试试这个:

def unique_animals(zoo, list_of_zoos):
    animals_in_other_zoos = set()
    for element of list_of_zoos:
        animals_in_other_zoos.add(set(element))
    unique_animals = set(zoo)
    for element in unique_animals:
        if element in animals_in_other_zoos:
            unique_animals.remove(element)
    return unique_animals

我可以做一些对我们的案例更有用的事情,但我需要你的一些代码。

【讨论】:

    【解决方案2】:

    你也许可以用一套来做,但你真的不需要。您需要考虑如何组织数据,即数据结构。

    这里有一种方法:要找出只存在于一个动物园中的动物,您需要一个列表,为每只动物提供拥有它的动物园。因此,为每只动物构建这样一个动物园列表(我会使用字典来保存动物名称,但即使是常规列表也可以),然后只需查看每只动物并选择仅列出一个动物园的动物。

    【讨论】:

      【解决方案3】:

      我认为set 是你要找的。​​p>

      您可以添加和减去集合,找到它们的交集 因此,您需要找到动物园,其中一组动物的项目不在其他动物园的联合动物集中。如果你从动物园里的动物中减去所有其他动物,你得到了独特的动物。

      zoos = ['mouse,dog', 'dog,tiger,mouse', 'mouse,cat']
      for zoo in zoos:
          zoo_animal = set(zoo.split(','))
          other_zoo_animals = set(animal for z in zoos if z != zoo for animal in z.split(','))
          unique_animals = zoo_animal - other_zoo_animals
          if unique_animals:
             print "%s: %s" % (zoo, unique_animals)
      

      或者您可以找出每只动物的生活地点:

      zoos = ['mouse,dog', 'dog,tiger,mouse', 'mouse,cat']
      animals = {}
      for i, zoo in enumerate(zoos):
          zoo_animal = set(zoo.split(','))
          for animal in zoo_animals:
              animals.setdefault(animal, []).append(i)
      # Now You can iterate over all animals and find ones which are only present in one zoo
      for animal, zoo_list in animals.iteritems():
          if len(zoo_list) == 1:
              print("% lives in %s only" % (animal, zoo_list[0]))
      

      【讨论】:

        【解决方案4】:

        如果我理解正确,你会得到这样的字符串:

        input_date = 'dog dog mouse cat, dog pidgin elephant, zebra cat lion'
        zoos = input_date.split(',')
        
        for zoo in zoos:
            zoo_animal = set(zoo.split())
            other_zoo_animals = set(animal for z in zoos if z != zoo for animal in z.split())
            unique = zoo_animal - other_zoo_animals
            if unique:
               print "%s: %s" % (zoo, animals)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-04-12
          • 2011-05-23
          • 2023-03-31
          • 2022-12-03
          • 2016-09-10
          • 1970-01-01
          • 2016-05-26
          相关资源
          最近更新 更多