更改列表列表中的所有字符串,但最后一个元素

发布于 2025-02-04 11:05:41 字数 292 浏览 1 评论 0原文

我正在尝试使用列表理解来创建一个新的字符串列表,其中所有字符串都将较低。这将是关键路线,但它降低了所有字符串:

[[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 技术交流群。

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

发布评论

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

评论(2

瑾兮 2025-02-11 11:05:41

您可以简单地添加最后一个切片:

[[word.lower() for word in words[:-1]] + words[-1:] for words in lists]

例如,

lists = [["FOO", "BAR", "BAZ"], ["QUX"], []]

输出为:

[['foo', 'bar', 'BAZ'], ['QUX'], []]

You can simply add back the last slice:

[[word.lower() for word in words[:-1]] + words[-1:] for words in lists]

For example, with

lists = [["FOO", "BAR", "BAZ"], ["QUX"], []]

the output is:

[['foo', 'bar', 'BAZ'], ['QUX'], []]
过期情话 2025-02-11 11:05:41

地图str.慢速直到倒数第二个元素,并在理解中的列表中解开映射对象,

# map str.lower to every element until the last word
# and unpack it in a list along with the last word
[[*map(str.lower, words[:-1]), words[-1]] for words in lists]

如果子列表可以为空(如Wjandrea的示例中),然后添加有条件的检查(尽管这是不那么可读和彻头彻尾的不良代码)

[[*map(str.lower, words[:-1]), words[-1]] if words else [] for words in lists]

Map str.lower until the penultimate element and unpack the map object in a list inside a comprehension

# map str.lower to every element until the last word
# and unpack it in a list along with the last word
[[*map(str.lower, words[:-1]), words[-1]] for words in lists]

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)

[[*map(str.lower, words[:-1]), words[-1]] if words else [] for words in lists]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文