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

Change all strings in list of lists but the last element

我正在尝试使用列表理解来创建一个新的字符串列表列表,其中除最后一个字符串外的所有字符串都将小写。这将是关键行,但它将所有字符串小写:

[[word.lower() for word in words] for words in lists]

如果我这样做:

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

省略了最后一个元素。

一般来说,如果列表很长,理解是best/fastest方法吗?

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

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

例如,与

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

输出是:

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

Map str.lower 直到倒数第二个元素并将 map 对象解包到理解列表中

# 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]

如果 sub-list 可以为空(如 wjandrea 的示例),则添加一个条件检查(尽管这样的可读性差得多并且是彻头彻尾的错误代码)

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