For example:
lst1 = ['wer12', 'rtgdf12', 'werfd12'] How to make it happen:
lst1 = ['wer','rtgdf','werfd'] For example:
lst1 = ['wer12', 'rtgdf12', 'werfd12'] How to make it happen:
lst1 = ['wer','rtgdf','werfd'] That's through generators:
lst1 = ['wer12', 'rtgdf12', 'werfd12'] lst1 = [str[:-2] for str in lst1] print(lst1) The map function bypasses all elements of the list and cuts all characters to the last two of each line:
res = map(lambda x: x[:-2], lst1) print(list(res)) You can use slices to get part of a string.
lst1 = list( map( lambda x : x[:-2], lst1 ) ) lambda x: x [: - 2] is an anonymous function that returns a string without the last 2 characters.
map --- applies the function to each element of the list, returns an iterator on the results of the function
list --- translates an iterator into a list
UPDATE:
lambda is a python constructor for creating anonymous functions
# такая запись lambda x: x[:-2] # аналогична такой, def f(x): return x[:-2] # с той лишь разницей, что не будет занято имя `f` Source: https://ru.stackoverflow.com/questions/590544/
All Articles