Python Yield 从单元素元组中返回字符而不是字符串
我使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只有 1 个元素的元组应该是 以逗号结尾书写。
A tuple having only 1 element should be written with a trailing comma.
您从未告诉循环您有一个列表,因此它将字符串视为序列。
编辑:或者您可以按照建议修复元组...我假设您想使用列表而不是元组。
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.