如何打印列表中的所有元素
我需要能够打印随机选择的列表中的所有元素,而不需要括号或逗号。我尝试使用“+”运算符打印每个元素,但它引发了无法将列表转换为字符串的错误。现在这是我的代码:
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])
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])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
print
函数可以接受多个参数。您不想尝试将所有内容粘在一起,因为它们是不同的类型 - 只需让 Python 按顺序打印它们即可。当然,这有点笨拙,并不能真正反映意图。幸运的是,有一个快捷方式可以让我们将列表中的所有项目作为参数提供给函数:
或者,因为我们实际上不再需要该名称,只需:
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.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:
Or, since we don't really need that name any more, just:
我认为这可能更接近您想要的:
This is probably closer to what you want, I think:
您应该将随机选择的结果保存在变量中,然后迭代其成员并按顺序打印。
You should save the result of random choice in a variable, then iterate over its members and print in order.
问题是您有一堆不同类型的元素并且想要打印它们。您应该做的是创建一个您想要的数据字符串并打印它。
像这样:
其他任何东西几乎只适合调试。喜欢:
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:
Anything else is pretty much only suitable for debugging. Like: