我有一个带有书籍信息的JSON文件。 在原始文件中还有更多。
示例:
[{"author": "Wes McKinney", "price": 53, "title": "Python for Data Analysis", "publication_year": "2012", "topic": "programming"},
{"author": "Joel Grus", "price": 66, "title": "Data Science from Scratch", "publication_year": "2015", "topic": "Python"}]
现在我想根据作者的姓氏对信息进行排序。 我做了以下事情:
names = []
for a in jsondata:
names.append(str.split((a['author'])))
print (sorted(names))
然后我得到这样的信息:
[['Allan', 'Downey'], ['Allan', 'Downey']
我想知道是否有人可以给我一个提示/提示如何使用我如何根据作者的姓氏对所有信息进行排序。
答案 0 :(得分:1)
您可以使用sorted()
将lambda
表达式排序为JSON结构:
lambda x: x["author"].split()[-1]
# split value of "author", key and sort based on the last word
无需显式迭代列表,并创建另一个列表来维护名称。
示例运行:
>>> my_json = [
{"author": "Wes McKinney", "price": 53, "title": "Python for Data Analysis", "publication_year": "2012", "topic": "programming"},
{"author": "Joel Grus", "price": 66, "title": "Data Science from Scratch", "publication_year": "2015", "topic": "Python"}
]
>>> sorted(my_json, key=lambda x: x["author"].split()[-1])
[{'topic': 'Python', 'price': 66, 'title': 'Data Science from Scratch', 'publication_year': '2015', 'author': 'Joel Grus'}, {'topic': 'programming', 'price': 53, 'title': 'Python for Data Analysis', 'publication_year': '2012', 'author': 'Wes McKinney'}]
答案 1 :(得分:0)
试试这个:
names = []
for a in jsondata:
last_name = a["author"].split(" ")[1]
names.append(last_name)
print(sorted(names))
如果您想要排序字典,可以这样做:
for a in sorted(jsondata, key=lambda x: x["author"].split(" ")[1]):
# You can use dict any way you like. E.g.:
print(a["title"] + " " + str(a["price"]))
答案 2 :(得分:0)
您只需要使用适当的键函数对jsondata
列表进行排序,该函数从与每个dict的“author”键关联的值中提取姓氏。
我使用了.rsplit
方法,因此我们可以有效地处理拥有2个以上名字的suthors。 .rsplit(None, 1)
将字符串从右侧分割为空格,使(最多)一个分割,返回包含(最多)两个元素的列表。姓氏将是该列表的最后一个元素。如果您希望“Guido Van Rossum”的姓氏为“Van Rossum”,那么您需要使用不同的分割策略。
import json
jsondata = [
{
"author": "Wes McKinney", "price": 53,
"title": "Python for Data Analysis",
"publication_year": "2012", "topic": "programming"
},
{
"author": "Joel Grus", "price": 66,
"title": "Data Science from Scratch",
"publication_year": "2015", "topic": "Python"
},
{
"author": "One",
},
{
"author": "Person With A Long Name",
},
]
def last_name(d):
return d["author"].rsplit(None, 1)[-1]
# Verify that `last_name` does what we want
for d in jsondata:
print(last_name(d))
jsondata.sort(key=last_name)
print(json.dumps(jsondata, indent=4))
<强>输出强>
McKinney
Grus
One
Name
[
{
"title": "Data Science from Scratch",
"author": "Joel Grus",
"topic": "Python",
"publication_year": "2015",
"price": 66
},
{
"title": "Python for Data Analysis",
"author": "Wes McKinney",
"topic": "programming",
"publication_year": "2012",
"price": 53
},
{
"author": "Person With A Long Name"
},
{
"author": "One"
}
]