gpt4 book ai didi

python - 使用函数将字符串添加到列表中的每个项目

转载 作者:行者123 更新时间:2023-12-04 03:09:10 24 4
gpt4 key购买 nike

因此,我的老师要我编写一个程序,使用两个函数将“名人堂成员”添加到列表中的每个棒球运动员。我们应该从这个打印列表中每个玩家的名字的程序开始:

def show_players(players):
"""Show list of baseball players"""
for player in players:
print(player.title())

baseball_players = ['jackie robinson', 'babe ruth', 'barry bonds']
show_players(baseball_players)

我们必须编写另一个函数,为每个球员添加“名人堂成员”,这就是我所拥有的(它不符合我的意愿):

def show_players(players):
"""Show list of baseball players"""
for player in players:
print(player.title())

def make_HOF(baseball_players):
"""Make each baseball player a Hall of Famer"""
HOF = "Hall of Famer "
for player in baseball_players:
HOF_players = [HOF + player]
return HOF_players

HOF_players = []
baseball_players = ['jackie robinson', 'babe ruth', 'barry bonds']
make_HOF(baseball_players)
show_players(HOF_players)

最佳答案

当您输入 HOF_players = [HOF + player] 时,它不会向您的列表中添加任何内容,而是添加字符串和列表,但未达到您的预期。尝试 HOF_players.append(HOF + player),这样它将字符串 'Hall of Famer' 添加到字符串 baseball_players[players] 并将其添加到列表中。

def show_players(players):
"""Show list of baseball players"""
for player in players:
print(player.title())

baseball_players = ['jackie robinson', 'babe ruth', 'barry bonds']
show_players(baseball_players)

def make_HOF(baseball_players):
"""Make each baseball player a Hall of Famer"""
HOF = "Hall of Famer "
for player in baseball_players:
HOF_players.append(HOF + player)
return HOF_players

HOF_players = []
make_HOF(baseball_players)
show_players(HOF_players)

如果问题解决了,谢谢。

关于python - 使用函数将字符串添加到列表中的每个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46657482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com