Reputation: 69
I need to be able to print all of the elements in a randomly chosen list without the brackets or commas. I tried to print each element with the '+' operator but it raised an error about not being able to convert the list to a string. Here is my code now:
t1 = ["rock", 80, 1,2,1]
t2 = ["carpet", 75, 2, 2, 1]
t3 = ["lava", 1000, 1, 1, 1]
t4 = ["rock", 90, 2, 1, 1]
Tiles = [t1, t2, t3, t4]
print(random.choice(Tiles)[0] + [1] + [2] + [3] + [4])
Upvotes: 0
Views: 6374
Reputation: 172229
The problem is that you have a bunch of elements of different types and want to print them. What you should do is make a string of the data you want and print that.
Something like this:
>>> import random
>>> tiles = [
... ["rock", 80, 1,2,1],
... ["carpet", 75, 2, 2, 1],
... ["lava", 1000, 1, 1, 1],
... ["rock", 90, 2, 1, 1],
... ]
>>> tile = random.choice(tiles)
>>> print("The random tile is '{0}', with the values {1}, {2}, {3} and {4}".format(*tile))
The random tile is 'rock', with the values 80, 1, 2 and 1
Anything else is pretty much only suitable for debugging. Like:
>>> print(*tile)
rock 80 1 2 1
Upvotes: 0
Reputation: 61509
The print
function can take multiple arguments. You don't want to try to stick everything together, because they're of different types - just let Python print them out in order.
title = random.choice(Titles)
print(title[0], title[1], title[2], title[3], title[4])
Of course, that's a bit unwieldy, and doesn't really reflect the intent. Fortunately, there is a shortcut that lets us feed all the items of a list as parameters to a function:
title = random.choice(Titles)
print(*title)
Or, since we don't really need that name any more, just:
print(*random.choice(Titles))
Upvotes: 3
Reputation: 47988
This is probably closer to what you want, I think:
print ' '.join(map(unicode, random.choice(Tiles)))
Upvotes: 2
Reputation: 1268
>>> import random
>>> t1 = ["rock", 80, 1,2,1]
>>> t2 = ["carpet", 75, 2, 2, 1]
>>> t3 = ["lava", 1000, 1, 1, 1]
>>> t4 = ["rock", 90, 2, 1, 1]
>>> Tiles = [t1, t2, t3, t4]
>>> print(random.choice(Titles)[0])
"rock"
Upvotes: 0
Reputation: 28292
You should save the result of random choice in a variable, then iterate over its members and print in order.
Upvotes: 0