更改列表列表中的所有字符串,但最后一个元素
我正在尝试使用列表理解来创建一个新的字符串列表,其中所有字符串都将较低。这将是关键路线,但它降低了所有字符串:
[[word.lower() for word in words] for words in lists]
如果我这样做:
[[word.lower() for word in words[:-1]] for words in lists]
省略了最后一个元素。
通常,如果列表相当长,那么理解是最好/最快的方法吗?
I am trying to use list comprehension to create a new list of lists of strings in which all strings but the last will be lowercased. This would be the critical line, but it lowercase all strings:
[[word.lower() for word in words] for words in lists]
If I do this:
[[word.lower() for word in words[:-1]] for words in lists]
the last element is omitted.
In general, if the list is rather long, is comprehension the best/fastest approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以简单地添加最后一个切片:
例如,
输出为:
You can simply add back the last slice:
For example, with
the output is:
地图str.慢速直到倒数第二个元素,并在理解中的列表中解开映射对象,
如果子列表可以为空(如Wjandrea的示例中),然后添加有条件的检查(尽管这是不那么可读和彻头彻尾的不良代码)
Map str.lower until the penultimate element and unpack the map object in a list inside a comprehension
If a sub-list can be empty (as in wjandrea's example), then add a conditional check (although this is far less readable and downright bad code)