[英]Change all strings in list of lists but the last element
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?一般来说,如果列表很长,理解是最好/最快的方法吗?
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: output 是:
[['foo', 'bar', 'BAZ'], ['QUX'], []]
Map str.lower until the penultimate element and unpack the map object in a list inside a comprehension Map str.lower 直到倒数第二个元素并将 map object 解压缩到一个列表中
# 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)如果子列表可以为空(如 wjandrea 的示例),则添加一个条件检查(尽管这是可读性差得多且完全错误的代码)
[[*map(str.lower, words[:-1]), words[-1]] if words else [] for words in lists]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.