python - Python标识符中的无效字符
问题描述
下面的 python 代码在标识符中出现错误无效字符。知道为什么吗?它是一个未完成的函数,我正在编写并提前返回 None,因为由于这个错误它没有运行。
def spotifyrecs(mylibrary, newsongs):
total = 0
count = 0
genredict = {}
for artist in mylibrary:
artistsongs = mylibrary[artist]
for adict in artistsongs:
total += adict["plays"]
count += 1
if adict["genre"] not in genredict:
genredict[adict["genre"]] = 1
if adict["genre"] in genredict:
genredict[adict["genre"]] += 1
avgplays = round(total / count, 2)
genrelist = []
for genre in genredict:
newtup = (genredict[genre], genre)
genrelist.append(newtup)
genrelist.sort(reverse = True)
return None
library = {"Ariana Grande": [{"title": "thank u, next", "plays": 100, "genre": "pop"}, {"title": "Last Christmas", "plays": 44, "genre": "Christmas"}], "Khalid":[{"title": "Location", "plays": 15, "genre": "R&B"}, {"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}]}
songs = [{"title": "Loving is Easy", "artist": "Rex Orange County", "plays": 115, "genre": "R&B"}, {"title": "Halo", "artist": "Beyonce", "plays": 9, "genre": "R&B"}, {"title": "Focus", "artist": "Ariana Grande", "plays": 112, "genre": "pop"}, {"title": "Winter", "artist": "Khalid", "plays": 800, "genre": "R&B"}]
print(spotifyrecs(library, songs))
错误:
File "so.py", line 22
library = {"Ariana Grande": [{"title": "thank u, next", "plays": 100, "genre": "pop"}, {"title": "Last Christmas", "plays": 44, "genre": "Christmas"}], "Khalid":[{"title": "Location", "plays": 15, "genre": "R&B"}, {"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}]}
^
SyntaxError: invalid character in identifier
解决方案
您的输入中有一个非打印字符:去掉 <200b> 字符,这运行得很好。
library = <200b>{
"Ariana Grande": [
{"title": "thank u, next", "plays": 100, "genre": "pop"},
{"title": "Last Christmas", "plays": 44, "genre": "Christmas"}
],
"Khalid":[
{"title": "Location", "plays": 15, "genre": "R&B"},
{"title": "Young, Dumb, and Broke", "plays": 90, "genre": "R&B"}
]}
请注意,它有助于使您的程序更具可读性。将其分离到单独的行并很好地缩进做了两件事:(1)解析器给了我一个更好的位置,因为它可以在行尾发出错误消息;(2) 通过这种方式,我可以更轻松地查找简单的拼写错误和括号平衡。
推荐阅读
- arrays - Ansible:在每次迭代时构建一个对象数组
- javascript - 如何获取城市和机场的完整列表及其相应的代码?
- html - 冻结表格中的第一列,并在标题行设置为换行空白处保持一致的高度?
- nginx - Magento2 内部页面在 nginx 上为多存储重定向 404
- android - 当应用程序来自后台时,始终会触发 Spinner 的 onItemSelected()
- c - 这段代码有什么问题?我是 CodeChef 的新手,它说我的输出不正确
- javascript - 输入控件值未从 ngModelChange 正确更新
- javascript - 递归函数最后总是返回 undefined。怎么修?
- javascript - Animate CC - if Else 语句
- salesforce - 在 apex 类中通过 docusign api 发送信封时出错