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



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

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

如果我这样做:

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

省略最后一个元素。

一般来说,如果列表很长,理解是最好/最快的方法吗?

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

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

例如,用

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

输出为:

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

映射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]

如果子列表可以为空(如wjandrea的示例),则添加条件检查(尽管这远不如可读性和彻头彻尾的糟糕代码)

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

最新更新