2016-02-21 20 views
7

Tôi đã tạo danh sách này; mỗi mục là một chuỗi có chứa dấu phẩy (trong một số trường hợp) và dấu hai chấm (luôn luôn):Sử dụng các hàm bậc cao của Python để thao tác các danh sách

dinner = [ 
    'cake,peas,cheese : No', 
    'duck,broccoli,onions : Maybe', 
    'motor oil : Definitely Not', 
    'pizza : Damn Right', 
    'ice cream : Maybe', 
    'bologna : No', 
    'potatoes,bacon,carrots,water: Yes', 
    'rats,hats : Definitely Not', 
    'seltzer : Yes', 
    'sleeping,whining,spitting : No Way', 
    'marmalade : No' 
] 

Tôi muốn tạo ra một danh sách mới từ một bên trên như sau:

['cake : No', 
'peas : No', 
'cheese : No', 
'duck : Maybe', 
'broccoli : Maybe', 
'onions : Maybe', 
'motor oil : Definitely Not', 
'pizza : Damn Right', 
'ice cream : Maybe', 
'bologna : No', 
'potatoes : Yes', 
'bacon : Yes', 
'carrots : Yes', 
'water : Yes', 
'rats : Definitely Not', 
'hats : Definitely Not', 
'seltzer : Yes', 
'sleeping : No Way', 
'whining : No Way', 
'spitting : No Way', 
'marmalade : No'] 

Nhưng tôi muốn biết liệu có thể làm như thế trong một hoặc hai dòng mã hiệu quả sử dụng chủ yếu các hàm bậc cao của Python. Tôi đã cố gắng nó:

reduce(lambda x,y: x + y, (map(lambda x: x.split(':')[0].strip().split(','), dinner)))

... sản xuất này:

['cake', 
'peas', 
'cheese', 
'duck', 
'broccoli', 
'onions', 
'motor oil', 
'pizza', 
'ice cream', 
'bologna', 
'potatoes', 
'bacon', 
'carrots', 
'water', 
'rats', 
'hats', 
'seltzer', 
'sleeping', 
'whining', 
'spitting', 
'marmalade'] 

... nhưng tôi đang phải vật lộn với phụ thêm mảnh mỗi chuỗi sau dấu hai chấm lại vào mỗi mục.

+0

Tại sao các bạn quan tâm về độ dài mã? Điều này sẽ ít được duy trì hơn trong dài hạn. – jpmc26

+0

@ jpmc26 Tôi hiểu bạn đến từ đâu và đồng ý. Điều này đối với tôi là một bài tập khám phá nhiều hơn trong việc hiểu các khả năng của hofs của Python. – dstar

Trả lời

3

Giả sử bạn thực sự cần nó như là một danh sách các chuỗi vs một cuốn từ điển , trông giống như một cấu trúc dữ liệu tốt hơn.

Bằng cách đơn giản hóa sử dụng comprehensions bạn có thể làm điều này:

>>> [[x+':'+y for x in i.split(',')] 
... for i, y in map(lambda l: map(str.strip, l.split(':')), dinner)] 
[['cake:No', 'peas:No', 'cheese:No'], 
['duck:Maybe', 'broccoli:Maybe', 'onions:Maybe'], 
['motor oil:Definitely Not'], 
... 
['marmalade:No']] 

Bây giờ chỉ cần add lên danh sách:

>>> from operator import add 
>>> reduce(add, ([x+':'+y for x in i.split(',')] 
...    for i, y in map(lambda l: map(str.strip, l.split(':')), dinner)), []) 
['cake:No', 
'peas:No', 
'cheese:No', 
'duck:Maybe', 
... 
'marmalade:No'] 

Hoặc chỉ cần san bằng danh sách:

>>> [a for i, y in map(lambda l: map(str.strip, l.split(':')), dinner) 
... for a in (x+':'+y for x in i.split(','))] 
['cake:No', 
'peas:No', 
'cheese:No', 
'duck:Maybe', 
... 
'marmalade:No'] 
+0

'flatten' được tích hợp dưới dạng' itertools.chain.from_iterable' – Caridorc

+0

@AChampion cảm ơn bạn. Một số người đã đăng mã tuyệt vời hoạt động tốt nhưng phản hồi của bạn phù hợp hơn với mục tiêu của tôi. – dstar

8

tôi sẽ tạo ra một dict sử dụng, zip, mapitertools.repeat:

from itertools import repeat 


data = ({k.strip(): v.strip() for _k, _v in map(lambda x: x.split(":"), dinner) 
    for k, v in zip(_k.split(","), repeat(_v))}) 

from pprint import pprint as pp 

pp(data) 

Output:

{'bacon': 'Yes', 
'bologna': 'No', 
'broccoli': 'Maybe', 
'cake': 'No', 
'carrots': 'Yes', 
'cheese': 'No', 
'duck': 'Maybe', 
'hats': 'Definitely Not', 
'ice cream': 'Maybe', 
'marmalade': 'No', 
'motor oil': 'Definitely Not', 
'onions': 'Maybe', 
'peas': 'No', 
'pizza': 'Damn Right', 
'potatoes': 'Yes', 
'rats': 'Definitely Not', 
'seltzer': 'Yes', 
'sleeping': 'No Way', 
'spitting': 'No Way', 
'water': 'Yes', 
'whining': 'No Way'} 

Hoặc sử dụng các nhà xây dựng dict:

from itertools import repeat 

data = dict(map(str.strip, t) for _k, _v in map(lambda x: x.split(":"), dinner) 
      for t in zip(_k.split(","), repeat(_v))) 

from pprint import pprint as pp 

pp(data) 

Nếu bạn thực sự muốn một danh sách các chuỗi, chúng ta có thể làm một cái gì đó tương tự bằng cách sử dụng itertools.chain và tham gia các chuỗi con:

from itertools import repeat, chain 

data = chain.from_iterable(map(":".join, zip(_k.split(","), repeat(_v))) 
          for _k, _v in map(lambda x: x.split(":"), dinner)) 


from pprint import pprint as pp 

pp(list(data)) 

Output:

['cake: No', 
'peas: No', 
'cheese : No', 
'duck: Maybe', 
'broccoli: Maybe', 
'onions : Maybe', 
'motor oil : Definitely Not', 
'pizza : Damn Right', 
'ice cream : Maybe', 
'bologna : No', 
'potatoes: Yes', 
'bacon: Yes', 
'carrots: Yes', 
'water: Yes', 
'rats: Definitely Not', 
'hats : Definitely Not', 
'seltzer : Yes', 
'sleeping: No Way', 
'whining: No Way', 
'spitting : No Way', 
'marmalade : No'] 
1

này có thể làm việc:

def processList (aList): 
    finalList = [] 
    for aListEntry in aList: 
     aListEntry_entries = aListEntry.split(':') 
     aListEntry_list = aListEntry_entries[0].split(',') 
     for aListEntry_list_entry in aListEntry_list: 
      finalList.append(aListEntry_list_entry.strip() + ' : ' + aListEntry_entries[1].strip()) 
    return finalList 
1

Danh sách comprehensions được ưa thích trong Python (kiểm tra ví dụ this), do mức độ dễ đọc hơn (ít nhất là đối với một số;).

Mã chứng minh hai loại tổ chức hiểu danh sách, đầu tiên về cơ bản là chuỗi các hoạt động, trường còn lại tạo ra một danh sách từ hai vòng lồng nhau.

Nếu bạn làm cho dữ liệu của bạn ổn định hơn bằng cách thêm một không gian sau khi carrots, water, bạn có thể thoát khỏi hai .strip() cuộc gọi;)

dinner = [ 
    'cake,peas,cheese : No', 
    'duck,broccoli,onions : Maybe', 
    'motor oil : Definitely Not', 
    'pizza : Damn Right', 
    'ice cream : Maybe', 
    'bologna : No', 
    'potatoes,bacon,carrots,water : Yes', 
    'rats,hats : Definitely Not', 
    'seltzer : Yes', 
    'sleeping,whining,spitting : No Way', 
    'marmalade : No' 
] 

prefs = [(pref, items.split(',')) for items, pref in [it.split(" : ") for it in dinner]] 
[" : ".join([item, pref]) for pref, items in prefs for item in items] 
Các vấn đề liên quan