如何使用列表Python创建带下划线的子集列表

时间:2017-08-29 02:39:26

标签: python list subset list-comprehension

我有一个名为animals的列表,

animals = ["B_FOX", "A_CAT", "A_DOG", "A_MOUSE", 
         "B_DOG", "B_MOUSE", "C_DUCK", "C_FOX", "C_BIRD"]

并希望得到以下结果:

 A = ["A_CAT", "A_DOG", "A_MOUSE"]
 B = ["B_DOG", "B_MOUSE", "B_FOX"]
 C = ["C_DUCK", "C_FOX", "C_BIRD"]

我只能得到这样的字母或动物的子集列表:

  [species.split("_",1)[1] for species in animals]
  ['FOX', 'CAT', 'DOG', 'MOUSE', 'DOG', 'MOUSE', 'DUCK', 'FOX', 'BIRD']

  [letters.split("_",1)[0] for letters in animals]
  ['B', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C']

不确定我是否正确地提出了这个问题。任何帮助解决这个棘手的问题将不胜感激!

3 个答案:

答案 0 :(得分:3)

你可以建立单独的列表,每个首字母一个,但是,如果你有很多字母,这将是棘手的。您可以改为使用defaultdict

from collections import defaultdict

d = defaultdict(list)
animals = ["B_FOX", "A_CAT", "A_DOG", "A_MOUSE", 
     "B_DOG", "B_MOUSE", "C_DUCK", "C_FOX", "C_BIRD"]

for animal in animals:
   d[animal[0]].append(animal)
print(dict(d))

输出:

{'A': ['A_CAT', 'A_DOG', 'A_MOUSE'], 'C': ['C_DUCK', 'C_FOX', 'C_BIRD'], 'B': ['B_FOX', 'B_DOG', 'B_MOUSE']}

答案 1 :(得分:2)

您可以通过一次调用split来解压缩前缀和名称的值:

groups = {}
for animal in animals:
    prefix, name = animal.split("_")
    if prefix not in groups:
        groups[prefix] = []
    groups[prefix].append(animal)

print groups
  

{' A':[' A_CAT',' A_DOG',' A_MOUSE'],' C' :[' C_DUCK',' C_FOX',' C_BIRD'],' B':[' B_FOX',& #39; B_DOG',' B_MOUSE']}

如果需要,您可以稍后将dict解压缩为单个变量:

A = groups["A"]
B = groups["B"]
C = groups["C"]

如果你想摆脱前缀:

groups = {}
for animal in animals:
    prefix, name = animal.split("_")
    if prefix not in groups:
        groups[prefix] = []
    groups[prefix].append(name)

答案 2 :(得分:2)

根据第一个字母尝试itertools.groupby

import operator as op
import itertools as it


animals = [
    "B_FOX", "A_CAT", "A_DOG", "A_MOUSE", 
    "B_DOG", "B_MOUSE", "C_DUCK", "C_FOX", "C_BIRD"
]

A, B, C = [list(g) for _, g in it.groupby(sorted(animals), key=op.itemgetter(0))]

输出:

A
# ['A_CAT', 'A_DOG', 'A_MOUSE']

B
# ['B_DOG', 'B_FOX', 'B_MOUSE']

C
# ['C_BIRD', 'C_DUCK', 'C_FOX']

以下是关于groupby如何运作的post