How to print the first letter from a list of random names?
This is what I have done so far and I can print the names randomly but need to print the first letter and not the whole name.
import random
names = ['Ed Sheeran', 'Beyonce', 'Adele', 'Rhianna']
secure_random = random.SystemRandom()
print(secure_random.choice (names))
Randomize the list and then print the first character-
import random
names = ['Ed Sheeran', 'Beyonce', 'Adele', 'Rhianna']
random_names = random.sample(names, len(names))
#If you are okay with mutating the original list then look into "shuffle"
for name in random_names:
print(name[0])
Output-
E
R
A
B
您还可以使用:
print(random.choice(names)[0])
Just a quickie because this is that I think you're looking for. You can put them into a string on one line using
print(" ".join((f[0] for f in random.shuffle(names)))
Shuffle the array, and print the first letter of each
names_copy = list(names)
shuffled_names = random.shuffle(names_copy)
first_letters = [name[0] for name in shuffled_names]
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.