You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在一行中打印列表的值而非逐行打印?含Python代码示例

解决一行打印列表元素的问题

嘿,这问题很常见,我来帮你调整代码实现一行打印的需求!

首先,你的代码里check_friends()函数还未实现,我们正好把一行打印的逻辑放在这个函数里。核心是利用Python字符串的join()方法,它能高效地把列表元素拼接成带指定分隔符的字符串。

修改后的完整代码

myFriends = []

def check_friends():
    if not myFriends:
        print("You have no friends yet!")
        return
    # 用', '连接列表元素,再与前缀拼接输出
    print(f"My friends are {', '.join(myFriends)}")

def add_new_friend():
    while True:
        newFriend = input("Add your new friend (Enter blank to quit):")
        if newFriend == "":
            break
        elif newFriend == "check":
            check_friends()
        else:
            myFriends.append(newFriend)

# 启动交互流程
add_new_friend()

# 如果退出交互后想直接打印所有好友,可取消下面这行的注释
# check_friends()

关键逻辑说明

  • ', '.join(myFriends):这个方法会遍历myFriends列表,把每个元素用, (逗号加空格)连接成一个完整字符串。比如列表为["Kate", "Matt"]时,会生成"Kate, Matt"。
  • f-string格式化输出:通过f"My friends are {拼接后的字符串}",轻松把前缀和好友列表组合成你需要的格式。
  • 空列表判断:当还未添加任何好友时输入check,会输出友好提示,避免出现My friends are 这种不完整的内容。

内容的提问来源于stack exchange,提问作者user9440272

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:25:44