我对蟒蛇的世界很陌生,尤其是字典,所以很可能我的问题答案很简单,但我真的搞不懂。
我的问题是,当我有一个字典时,我似乎不知道如何在某个位置访问一个特定的list元素,因为它的值具有列表。
更具体地说,我有以下清单:
my_books = {'Eragon': [2007,'Paolin'], 'Harry Potter': [1992,'Rowling'], 'Obscura': [2017, 'Canon'], 'Many Wonders': [1964,'Meyers'], 'Never': [2001, 'McKey']}我现在想要实现的是,它在一个非常简单的、按字母顺序排序的表中返回列表位置1的值和书的标题(键)。
所需产出:
Canon Obscura
McKey Never
Meyers Many Wonders
Paolin Eragon
Rowling Harry Potter我似乎搞不明白的是,如何只在第1位置打印list元素,而不是打印整个列表。
我的代码:
for book in my_books:
print(my_books[book], ' ', book)我的产出:
[2007,'Paolin'] Eragon
[1992,'Rowling'] Harry Potter
[2017, 'Canon'] Obscura
[1964,'Meyers'] Many Wonders
[2001, 'McKey'] Never无论如何,如果你们中的任何一个能帮助我,我会非常感激的!
发布于 2022-10-30 11:46:29
author_book = sorted([(my_books[book][1], book) for book in my_books])
for author, book in author_book:
print(f"{author:10}{book}")解释如下:
- By default, tuples are sorted by their first elements (authors).(在同一个作者的情况下,他们的第二个元素被用作第二个排序键)。
- The `my_books[book][1]` part of the list comprehension means that - we use the `book` key to obtain its value(`my_books[book]`), and
- because this value is a list with the _author name in the position_ _`1`_ (counting from zero), we append `[1]` to obtain the author name.在第二个命令中,我们使用带有格式的f-string,为作者保留足够(10)个位置,以达到良好的列格式。
发布于 2022-10-30 11:37:38
首先,你需要根据作者的名字对字典进行排序。然后迭代排序的键并以格式化的方式打印所需的参数。例如:
my_books = {
"Eragon": [2007, "Paolin"],
"Harry Potter": [1992, "Rowling"],
"Obscura": [2017, "Canon"],
"Many Wonders": [1964, "Meyers"],
"Never": [2001, "McKey"],
}
for key in sorted(my_books, key=lambda k: my_books[k][1]):
print("{:<15} {:<15}".format(my_books[key][1], key))指纹:
Canon Obscura
McKey Never
Meyers Many Wonders
Paolin Eragon
Rowling Harry Potter 发布于 2022-10-30 11:50:30
@Andrej Kesey的优秀答案的一个变体,它不需要lambda,而是依赖于元组的自然排序过程:
my_books = {
"Eragon": [2007, "Paolin"],
"Harry Potter": [1992, "Rowling"],
"Obscura": [2017, "Canon"],
"Many Wonders": [1964, "Meyers"],
"Never": [2001, "McKey"],
}
for author, title in sorted((value, key) for key, (_, value) in my_books.items()):
print(f'{author:<12}{title}')输出:
Canon Obscura
McKey Never
Meyers Many Wonders
Paolin Eragon
Rowling Harry Potterhttps://stackoverflow.com/questions/74252649
复制相似问题