如何根据键组合字典列表

时间:2019-03-30 17:16:09

标签: python python-3.x dictionary

使用此数据:

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]} ")

它以以下格式返回数据:

“我不怕计算机。我怕缺少计算机。” -艾萨克·阿西莫夫

这与我想要的非常接近,但是我确信这不是实现此目的的最佳方法。而且,我不知道如何反转名字和姓氏(或分别访问每个名字)。

谢谢!

3 个答案:

答案 0 :(得分:2)

使用带有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 :(得分:1)

逐步:

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

答案 2 :(得分:0)

为什么不这样:

>>> 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]

警告您不需要列表理解产生的列表。因此,这可能被视为不良做法。

相关问题