在我开始描述问题之前,我需要说,英语不是我的母语,所以,不幸的是,我可能会犯很多错误。感谢理解!
favourite_places = {
'Paris':['Jake','Carl'],
'London':'Jake',
'Moscow':'Fred',
}
for username,user_info in favourite_places.items():
print('======================')
print('Place: ' + username)
print('Who likes it: ' + user_info)
错误:
Type of error: TypeError: can only concatenate str (not "list") to str
我现在真的不知道如何修复它。当我清除 ['Carl']
时,程序开始工作,但我需要 ['Carl']
。请帮忙
答案 0 :(得分:2)
加入你的列表项以形成一个字符串:
favourite_places = {
'Paris':['Jake','Carl'],
'London':['Jake'],
'Moscow':['Fred']
}
for username,user_info in favourite_places.items():
print('======================')
print('Place: ' + username)
print('Who likes it: ' + ', '.join(user_info))
答案 1 :(得分:0)
您正在尝试打印“谁喜欢它:[杰克,卡尔]”
不出所料,python 不喜欢那样......
试试这个:
favourite_places = {
'Paris':['Jake','Carl'],
'London':['Jake'],
'Moscow':['Fred'],
}
for username,user_info in favourite_places.items():
print('======================')
print('Place: ' + username)
users = ""
for user in user_info:
users = users + user + ", "
users = users[:len(users)-2] #Ach, sure we'll stick this in too to clean up the last trailing comma & space we don't want
print('Who likes it: ' + users)
答案 2 :(得分:0)
制作所有字典值列表,以便在需要时可以将它们全部连接起来:
favourite_places = {
'Paris': ['Jake','Carl'],
'London': ['Jake'],
'Moscow': ['Fred'],
}
然后当您需要打印列表时,请使用 f 字符串:
print(f'Who likes it: {user_info}')
答案 3 :(得分:0)
错误语句说明了一切:您只能将 str(而不是“列表”)连接到 str。
您应该更改您的字典,以便每个值都是一个列表,可以使用一致的数据。
但是,采取懒惰的方式,您也可以简单地使用 f-string,如下面的最后一行:
for username,user_info in favourite_places.items():
print('======================')
print('Place: ' + username)
print(f"Who likes it: {user_info}")
输出:
======================
Place: Paris
Who likes it: ['Jake', 'Carl']
======================
Place: London
Who likes it: Jake
======================
Place: Moscow
Who likes it: Fred