簡體   English   中英

如何根據鍵組合字典列表

[英]How to combine list of dictionaries based on key

使用此數據:

famous_quotes = [
    {"full_name": "Isaac Asimov", "quote": "I do not fear computers. I fear lack of them."},
    {"full_name": "Emo Philips", "quote": "A computer once beat me at chess, but it was no match for me at "
                                          "kick boxing."},
    {"full_name": "Edsger W. Dijkstra", "quote": "Computer Science is no more about computers than astronomy "
                                                 "is about telescopes."},
    {"full_name": "Bill Gates", "quote": "The computer was born to solve problems that did not exist before."},
    {"full_name": "Norman Augustine", "quote": "Software is like entropy: It is difficult to grasp, weighs nothing, "
                                               "and obeys the Second Law of Thermodynamics; i.e., it always increases."},
    {"full_name": "Nathan Myhrvold", "quote": "Software is a gas; it expands to fill its container."},
    {"full_name": "Alan Bennett", "quote": "Standards are always out of date.  That’s what makes them standards."}
]

我正在嘗試以以下格式打印數據:

“鼓舞人心的報價”-姓,名

到目前為止,這是我得到的:

quote_names = [k['full_name'] for k in famous_quotes]
quote = [i['quote'] for i in famous_quotes]

print(f"\"{quote[0]}\" - {quote_names[0]} ")
print(f"\"{quote[1]}\" - {quote_names[1]} ")
print(f"\"{quote[2]}\" - {quote_names[2]} ")
print(f"\"{quote[3]}\" - {quote_names[3]} ")
print(f"\"{quote[4]}\" - {quote_names[4]} ")
print(f"\"{quote[5]}\" - {quote_names[5]} ")
print(f"\"{quote[6]}\" - {quote_names[6]} ")

它以以下格式返回數據:

“我不怕計算機。我怕缺少計算機。” -艾薩克·阿西莫夫(Isaac Asimov)

這與我想要的非常接近,但是我確定這不是實現此目的的最佳方法。 另外,我不知道如何顛倒名字和姓氏(或分別訪問每個名字)。

謝謝!

使用帶有f -string的循環來格式化字符串:

famous_quotes = [
    {"full_name": "Isaac Asimov", "quote": "I do not fear computers. I fear lack of them."},
    {"full_name": "Emo Philips", "quote": "A computer once beat me at chess, but it was no match for me at "
                                          "kick boxing."},
    {"full_name": "Edsger W. Dijkstra", "quote": "Computer Science is no more about computers than astronomy "
                                                 "is about telescopes."},
    {"full_name": "Bill Gates", "quote": "The computer was born to solve problems that did not exist before."},
    {"full_name": "Norman Augustine", "quote": "Software is like entropy: It is difficult to grasp, weighs nothing, "
                                               "and obeys the Second Law of Thermodynamics; i.e., it always increases."},
    {"full_name": "Nathan Myhrvold", "quote": "Software is a gas; it expands to fill its container."},
    {"full_name": "Alan Bennett", "quote": "Standards are always out of date.  That’s what makes them standards."}
]

for x in famous_quotes:
    print(f"\"{x['quote']}\" - {' '.join(reversed(x['full_name'].split()))}")

# "I do not fear computers. I fear lack of them." - Asimov Isaac                                                            
# "A computer once beat me at chess, but it was no match for me at kick boxing." - Philips Emo
# "Computer Science is no more about computers than astronomy is about telescopes." - Dijkstra W. Edsger                
# "The computer was born to solve problems that did not exist before." - Gates Bill                                       
# "Software is like entropy: It is difficult to grasp, weighs nothing, and obeys the Second Law of Thermodynamics; i.e., it always increases." - Augustine Norman                       
# "Software is a gas; it expands to fill its container." - Myhrvold Nathan                                                
# "Standards are always out of date.  That’s what makes them standards." - Bennett Alan

一步步:

1. Each quote is stored as a dictionary in array.
2. Iterate over the array
3.   we can access dictionary values by using key
4.   get the qoute
5.   get the full_name
6.   split it on spaces "a b c ".split(' ') = ['a','b','c']
7.   print the last element
8.   print the all elements except last element 

for single_qoute in famous_quotes:
    full_name_split = single_qoute['full_name'].split(' ')
    print(single_qoute['quote'],' -',full_name_split[-1],"".join(full_name_split[:-1]))     

輸出:

I do not fear computers. I fear lack of them.  - Asimov Isaac
A computer once beat me at chess, but it was no match for me at kick boxing.  - Philips Emo
Computer Science is no more about computers than astronomy is about telescopes.  - Dijkstra EdsgerW.
The computer was born to solve problems that did not exist before.  - Gates Bill
Software is like entropy: It is difficult to grasp, weighs nothing, and obeys the Second Law of Thermodynamics; i.e., it always increases.  - Augustine Norman
Software is a gas; it expands to fill its container.  - Myhrvold Nathan
Standards are always out of date.  That’s what makes them standards.  - Bennett Alan

為什么不這樣:

>>> for _ in famous_quotes:
...    print(f'"{_["quote"]}\" - {" ".join(_["full_name"].split(" ")[::-1])}')
"I do not fear computers. I fear lack of them." - Asimov Isaac
"A computer once beat me at chess, but it was no match for me at kick boxing." - Philips Emo
"Computer Science is no more about computers than astronomy is about telescopes." - Dijkstra W. Edsger
"The computer was born to solve problems that did not exist before." - Gates Bill
"Software is like entropy: It is difficult to grasp, weighs nothing, and obeys the Second Law of Thermodynamics; i.e., it always increases." - Augustine Norman
"Software is a gas; it expands to fill its container." - Myhrvold Nathan
"Standards are always out of date.  That’s what makes them standards." - Bennett Alan

為了更好地理解,可以將其擴展為:

for _ in famous_quotes:
    quote = _["quote"]
    name_list = _["full_name"].split(" ")    
    reversed_name = " ".join(name_list[::-1])    # name_list[::-1] does the same of name_list.reverse() but instead of change the current list, it returns a new list
    print(f'"{quote} - {reversed_name}')

或訂約給:

>>> [print(f'"{_["quote"]}\" - {" ".join(_["full_name"].split(" ")[::-1])}') for _ in famous_quotes]

警告您不需要列表理解所生成的列表。 因此,這可能被視為不良做法。

暫無
暫無

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

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