如何打印列表中的所有元素

时间:2011-07-25 22:52:29

标签: list printing python-3.x element

我需要能够在没有括号或逗号的情况下随机选择列表中的所有元素。我试图用'+'运算符打印每个元素,但它引发了一个错误,无法将列表转换为字符串。这是我现在的代码:

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])

6 个答案:

答案 0 :(得分:3)

print函数可以使用多个参数。你不想试图将所有东西粘在一起,因为它们的类型不同 - 只需让Python按顺序打印出来。

title = random.choice(Titles)
print(title[0], title[1], title[2], title[3], title[4])

当然,这有点笨拙,并没有真正反映出意图。幸运的是,有一个快捷方式可以让我们将列表中的所有项目作为参数提供给函数:

title = random.choice(Titles)
print(*title)

或者,因为我们不再需要这个名字,只需:

print(*random.choice(Titles))

答案 1 :(得分:2)

这可能更接近你想要的,我想:

print ' '.join(map(unicode, random.choice(Tiles)))

答案 2 :(得分:0)

您应该将随机选择的结果保存在变量中,然后迭代其成员并按顺序打印。

答案 3 :(得分:0)

>>> 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"

答案 4 :(得分:0)

问题是你有一堆不同类型的元素并想要打印它们。你应该做的是创建一个你想要的数据字符串并打印出来。

这样的事情:

>>> 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

其他任何东西都非常适合调试。像:

>>> print(*tile)
rock 80 1 2 1

答案 5 :(得分:-1)

print(repr(random.choice(Tiles))[1:-1].replace(',','  '))
相关问题