打印夸尔格斯以进行循环

发布于 2025-02-01 09:58:02 字数 367 浏览 4 评论 0原文

我一直在尝试执行此代码,以打印在循环中的关键字参数。我尝试使用f-string文字和.format()方法,但是它一次以2行的形式给出输出,一次为一个值。有人可以指出此代码中出了什么问题吗?

def myfunc(**kwargs):
    print(kwargs)
    for item in kwargs:
        print(f"my fruit of choice is : {kwargs['fruit']} and my veggie is: {kwargs['veggie']}")

myfunc(fruit='Apple',veggie='Lettuce')


I have been trying to execute this code for printing out the keyword argument in for loop. I tried using both the f-string literals and .format() method, but it is giving output in 2 lines taking one value at a time. Can someone please point out what is going wrong in this code?

def myfunc(**kwargs):
    print(kwargs)
    for item in kwargs:
        print(f"my fruit of choice is : {kwargs['fruit']} and my veggie is: {kwargs['veggie']}")

myfunc(fruit='Apple',veggie='Lettuce')


如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那小子欠揍 2025-02-08 09:58:02

如评论中所述,不需要带有两个项目的循环,但是这是一个带有循环的校正版本,可以适用于任意数量的输入:

def myfunc(**kwargs):
    print(kwargs)
    stringlist = []
    for i, item in enumerate(kwargs):
        if i == 0:
            string = f"my {item} of choice is: {kwargs[item]}"
        else:
            string = f"my {item} is: {kwargs[item]}"
        stringlist.append(string)
    stringlist[-1] = "and " + stringlist[-1]
    if len(kwargs) >= 3:
        print(', '.join(stringlist)+'.')
    else: 
        print(' '.join(stringlist)+'.')

myfunc(fruit='Apple',veggie='Lettuce')

我不会使用结肠,因为它们在语法上不正确,但是我把它们留在了您的原始预期输出中。

There's no need for the loop with two items, as mentioned in the comments, but here is a corrected version with a loop that will work for an arbitrary number of inputs:

def myfunc(**kwargs):
    print(kwargs)
    stringlist = []
    for i, item in enumerate(kwargs):
        if i == 0:
            string = f"my {item} of choice is: {kwargs[item]}"
        else:
            string = f"my {item} is: {kwargs[item]}"
        stringlist.append(string)
    stringlist[-1] = "and " + stringlist[-1]
    if len(kwargs) >= 3:
        print(', '.join(stringlist)+'.')
    else: 
        print(' '.join(stringlist)+'.')

myfunc(fruit='Apple',veggie='Lettuce')

I wouldn't use the colons, since they aren't grammatically correct, but I left them in to match your original expected output.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文