30344

[code]

    cars = [{'colors':'black,red,pink'},
            {'colors':'blue,yellow,green'},
            {'colors':'blue,red,gold,white'}]
    
[/code]

carsにはcolorsの他に色々なKeyと値が入っています。  
colorsの値は見たまんまの文字列が入っています。  
`blue,red,gold,white`

carsからcolorsのそれぞれ一色が入った辞書らを取り出すにはどうすればよいですか？  
色を選択してそれに該当する車等にフィルターをかけるということです。

[code]

    c = [x for car in cars for color in car['colors'].split(',')]
    # cは["black","red","pink","blue","yellow","green","blue","red","gold","white"]
    
    
    #   blue  2           重複を消したcolorsに多い順に並べた配列
    for key, count in collections.Counter(c).most_commons():
    
        # 失敗例
        print(dict(filter(lambda x: x in key, cars)))
    
[/code]

理想

[code]

    # red [{'colors':'blue,red,gold,white'},{'colors':'black,red,pink'}]
    #blue [{'colors':'blue,yellow,green'}, {'colors':'blue,red,gold,white'}]
    #pink [{'colors':'black,red,pink'}]
    
[/code]

わかりづらくて申し訳有りません。  
carsから20台選択する ＝ cars[:20]  
carsからredのある台数分を全て取得 = cars[colors['red']]


CC BY-SA 3.0
2016-11-12T06:40:12.280
30340
2016-11-12T08:07:51.640
2016-11-12T06:55:49.570
7973
7973
question
python
辞書の配列[{},{},{}]から特定の値が入ったやつらを取り出す[{},{}]


ジェネレータで

[code]

    from pprint import pprint
    
    cars = [{'colors':'black,red,pink'},
            {'colors':'blue,yellow,green'},
            {'colors':'blue,red,gold,white'}]
    
    def filter_by_color(cars, color):
        def extract_colors(car):
            return car.get('colors', '').split(',')
    
        for car in cars:
            if color in extract_colors(car):
                yield car
    
    pprint(list(filter_by_color(cars, 'red')))
    
    # [{'colors': 'black,red,pink'}, {'colors': 'blue,red,gold,white'}]
    
[/code]


CC BY-SA 3.0
2016-11-12T07:41:45.547
30341
2016-11-12T07:41:45.547
62
30340
answer


それではリスト内包表記と正規表現で。

[code]

    >>> import re
    
    >>> color = 'red'
    >>> [c for c in cars if re.search(r'(^|,)'+color+r'(,|$)', c['colors'])]
    [{'colors': 'black,red,pink'}, {'colors': 'blue,red,gold,white'}]
    
    >>> color = 'blue'
    >>> [c for c in cars if re.search(r'(^|,)'+color+r'(,|$)', c['colors'])]
    [{'colors': 'blue,yellow,green'}, {'colors': 'blue,red,gold,white'}]
    
    >>> color = 'pink'
    >>> [c for c in cars if re.search(r'(^|,)'+color+r'(,|$)', c['colors'])]
    [{'colors': 'black,red,pink'}]
    
[/code]


CC BY-SA 3.0
2016-11-12T08:07:51.640
30344
2016-11-12T08:07:51.640
30340
answer