简体   繁体   中英

Python program to print letter in an array backwards

I have to print letters from an array backwards. I got all the letters to be backwards but I realized I used the sort method and I'm not allowed to use it. I can't figure out any other way. Any suggestions?

The output should be:

w

v

u

t

.
.
.

g

f

This is the code I have so far:

letter = ['f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w']
letter.sort(reverse=True)





for i in range(len(letter)):
print(letter[i])
letter = ['f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w']
letter[::-1]

OR

reverseletter=letter[::-1]
letters = 'fghijklmnopqrstuvw'

for letter in reversed(letters):
    print(letter)
  • Strings work like lists. A string is a list of characters.
  • reversed() can be used to reverse the order of a list.
  • There is no need to use range()

you can use use the built-in function reversed :

print(*reversed(letter), sep='\n')

output:

w
v
u
t
s
r
q
p
o
n
m
l
k
j
i
h
g
f
  • *reversed(letter) will give as non-keyword arguments all the letters in reverse order for the print built-in function
  • the keyword argument sep='\\n' will ensure that all the letters will be printed on a separate line

To reverse a list you can use.

  1. Slicing [::-1]
for i in letters[::-1]:
    print(i)
  1. You can use reversed .
for i in reversed(letter):
    print(i)

Note: reversed spits an iterator .

you can use revered() method to print it in reverse order such as below

letter = ['f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w']

for i in reversed(letter): 
    print(i)

letterrev=letter[::-1]

for i in letterrev: print(i)

use this one

You can directly use list indexing or slicing such as:

letter = ['f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w']

print(letter[::-1])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM