这是我试图反转这些字符串的代码
presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]
reversedPresidents=""
for ch in presidents:
reversedPresidents=ch+reversedPresidents
print(reversedPresidents)
截至目前,它只会向后打印列表:
John Quincy Adams James Monroe James Madison Thomas Jefferson John Adams George Washington
我需要输出列表,如:
notgnihsaW egroeG
smadA nhoJ
等等
答案 0 :(得分:0)
试试这个:
>>> reversedPresidents = [p[::-1] for p in presidents]
>>> print(reversedPresidents)
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
>>>
答案 1 :(得分:0)
递归之美:
presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]
def reverse_list(list_1):
for item in list_1:
def reverse(word):
if len(word)==0:
return word
else:
return reverse(word[1:]) + word[0]
print(reverse(item))
print(reverse_list(presidents))
输出:
notgnihsaW egroeG
smadA nhoJ
nosreffeJ samohT
nosidaM semaJ
eornoM semaJ
smadA ycniuQ nhoJ
答案 2 :(得分:0)
你也可以试试这个:
>>> presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " , " James Madison " , " James Monroe " ," John Quincy Adams " ]
>>>> print(["".join(reversed(x)) for x in presidents])
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']
答案 3 :(得分:0)
试试这个:
presidents = [ "George Washington " , " John Adams " , " Thomas Jefferson " ,
" James Madison " , " James Monroe " ," John Quincy Adams " ]
reversedPresidents=[]
for ch in presidents:
reversedPresidents.append(ch[::-1])
print(reversedPresidents)
[' notgnihsaW egroeG', ' smadA nhoJ ', ' nosreffeJ samohT ', ' nosidaM
semaJ ', ' eornoM semaJ ', ' smadA ycniuQ nhoJ ']