Python Yield 从单元素元组中返回字符而不是字符串

发布于 2024-09-14 20:09:47 字数 277 浏览 15 评论 0原文

我使用 yield 来处理列表的每个元素。但是,如果元组只有一个字符串元素,yield 返回字符串的字符,而不是整个字符串:

self.commands = ("command1")
...
for command in self.commands:
        yield command            # returns 'c' not 'command1'

我该如何解决这个问题?

谢谢

I'm using yield to process each element of a list. However, if the tuple only has a single string element, yield returns the characters of the string, instead of the whole string:

self.commands = ("command1")
...
for command in self.commands:
        yield command            # returns 'c' not 'command1'

how can i fix this?

Thanks

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

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

发布评论

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

评论(2

橘寄 2024-09-21 20:09:47

只有 1 个元素的元组应该是 以逗号结尾书写

self.commands = ("command1",)

A tuple having only 1 element should be written with a trailing comma.

self.commands = ("command1",)
绿光 2024-09-21 20:09:47
self.commands = ["command1"]

您从未告诉循环您有一个列表,因此它将字符串视为序列。

编辑:或者您可以按照建议修复元组...我假设您想使用列表而不是元组。

self.commands = ["command1"]

You never told the loop that you had a list, so it's treating the string as the sequence.

edit: or you could just fix the tuple, as recommended ... I assumed you'd want to use a list instead of a tuple.

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