问题
For instance, myList = ['string1', 'string2', 'string3']
... now I want my result to be this:
['1gnirts', '2gnirts', '3gnirts']
I've found few examples on how to reverse strings in general but not specific to this problem ... I'm bit confused on how to do a reverse of strings that are in a list.
回答1:
reversed_strings = [x[::-1] for x in myList][::-1]
回答2:
There are two things you need to use, the reverse function for lists, and the [::-1] to reverse strings. This can be done as a list comprehension as follows.
myList.reverse
newList = [x[::-1] for x in myList]
回答3:
Or
oneShot = [x[::-1] for x in myList][::-1]
回答4:
If you already know how to reverse a single word, for this problem you only have to do the same for each of the words of the list:
def reverseWord(word):
# one way to implement the reverse word function
return word[::-1]
myList = ["string1", "string2", "string3"]
# apply the reverseWord function on each word using a list comprehension
reversedWords = [reverseWord(word) for word in myList]
来源:https://stackoverflow.com/questions/48952467/python-how-do-i-reverse-every-character-in-a-string-list