簡體   English   中英

如何在字典中使用map來小寫字符串?

[英]How to use map to lowercase strings in a dictionary?

我正在嘗試使用Python 3.6中的mapfilterreduce 我想要做的是,給定一個字典列表 ,將與某個鍵相關聯的所有值更改為小寫值。 例如:

message_one = {"content": "I'm glad I know sign language, it's pretty handy."}
message_two = {"content": "I am on a seafood diet. Every time I see food, I eat it."}
message_three = {"content": "Labyrinths are amazing."}
messages = [message_one , message_two , message_three]

print(to_lowercase(tweets))
#to_lowercase should just return the a list of dictionaries, but content lower-cased.

我首先嘗試使用地圖

def to_lowercase(messages):
    lower_case = map(lambda x: x["content"].lower(), messages)
    return lower_case

但是,這似乎只返回列表中所有內容消息的列表,並且不會保留字典格式。 我不認為在這種情況下reduce是正確的,因為我不打算在最后返回單個值,並且filter在這里似乎沒有意義。

我如何使用mapreducefilter來完成這項工作?

簡單的解決方案,使與小寫值新類型的字典列表:

dicts = [{k:v.lower() for k,v in d.items()} for d in messages]
print(dicts)

輸出:

[{'content': "i'm glad i know sign language, it's pretty handy."}, {'content': 'i am on a seafood diet. every time i see food, i eat it.'}, {'content': 'labyrinths are amazing.'}]

(注意,這個答案假設您正在使用Python 2;如果您使用的是Python 3,請考慮map()返回一個迭代器 ,您需要添加某種循環來查看結果)。

如果你堅持使用map() ,那么你想要創建一個新函數來應用於每個現有字典:

def dict_lowercase_content(d):
    """Produces a copy of `d` with the `content` key lowercased"""
    copy = dict(d)
    if 'content' in copy:
        copy['content'] = copy['content'].lower()
    return copy

def to_lowercase(tweets):
    return map(dict_lowercase_content, tweets)

dict_lowercase_content()不假設字典中存在哪些鍵; 它將創建所有鍵的淺表副本, 如果存在content鍵,則它是小寫的。

當然,如果你可以確定只有content鍵是重要的並且始終存在,你可以用這個鍵創建全新的詞典;

def to_lowercase(tweets):
    return map(lambda d: {'content': d['content'].lower()}, tweets)

如果就地更新字典很好(這會更有效),只需使用循環:

def to_lowercase(tweets):
    for tweet in tweets:
        if 'content' in tweet:
            tweet['content'] = tweet['content'].lower()

請注意,此函數返回None 這是Python慣例; 當就地修改可變對象時,不要再次返回這些對象,因為調用者已經有一個引用。

您不能對此作業使用reduce()filter()

  • filter() 從iterable中選擇元素 你沒有選擇,你正在改變。

  • reduce() 聚合元素 ; 輸入中的每個元素與運行結果一起傳遞給函數; 函數返回的任何內容都被視為更新結果。 想想總結,連接或遍歷樹。 同樣,你沒有聚合,你正在改變。

map

map(lambda x: {'content': x['content'].lower()}, messages)

沒有map

[{'content': x['content'].lower()} for x in messages]

沒有map ,但更健壯:

[{y: x[y].lower()} for x in messages for y in x]

map()是一個內置的高階函數,用於轉換集合。 我們提供一個匿名函數(lambda)來執行map,而不是將集合作為參數本身提供。 實現目標的一種方法是:

transformed_messages = list(map(lambda x: {'content':x['content'].lower()}, messages))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM