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:
[['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 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.