我是一名新手程序员,我不知道如何从我从带有列表的字典中提取的值中删除方括号和逗号。我错过了什么?
据我所知,for循环通常会删除它们,但现在不这样做。
简化代码:
dict = {
'name1': ['python', 'c', 'java'],
'name2': ['c.'],
'name3': ['ruby', 'go'],
'name4': ['javascript', 'python'],
'name5': [],
}
for k, v in dict.items():
if len(v) == 1:
print(str(k).title() + "'s favorite language is " + str(v).title() + "\n")
elif len(v) > 1:
print(str(k).title() + "'s favorite languages are: \n" + str(v).title() + "\n")
elif len(v) < 1 :
print(str(k).title() + " does not have a favorite language")
答案 0 :(得分:3)
dict = {
'name1': ['python', 'c', 'java'],
'name2': ['c.'],
'name3': ['ruby', 'go'],
'name4': ['javascript', 'python'],
'name5': [],
}
for k, v in dict.items():
if len(v) == 1:
print(str(k).title() + "'s favorite language is " + ', '.join(map(str.title, v)) + "\n")
elif len(v) > 1:
print(str(k).title() + "'s favorite languages are: \n" + ', '.join(map(str.title, v)) + "\n")
elif len(v) < 1 :
print(str(k).title() + " does not have a favorite language")
输出
Name3's favorite languages are:
Ruby, Go
Name5 does not have a favorite language
Name2's favorite language is C.
Name4's favorite languages are:
Javascript, Python
Name1's favorite languages are:
Python, C, Java
这个想法是将str.title
应用于值列表中的每个字符串(使用map),然后通过逗号和空格(', '
)将这些字符串连接起来。请注意,您可以更改连接的字符串以适合您的需求。
答案 1 :(得分:1)
尽管Daniel的回答更加优雅和完整,但我想解决您的问题,即为什么“ for”功能没有拆分语言名称(删除“,”和“]”)。代码中的第一个“ for”函数会遍历字典。如果您只想使用“ for”功能,则需要针对每个人的条目再次重用它以分隔语言。像下面的代码示例。
dict = {
'name1': ['python', 'c', 'java'],
'name2': ['c.'],
'name3': ['ruby', 'go'],
'name4': ['javascript', 'python'],
'name5': [],
}
for k, v in dict.items():
if len(v) == 1:
print(str(k).title() + "'s favorite language is " + str(v).title() + "\n")
elif len(v) > 1:
print(str(k).title() + "'s favorite languages are:")
for language in v:
print(language + ", ")
print("")
elif len(v) < 1 :
print(str(k).title() + " does not have a favorite language")