在Python中以以下格式打印列表<word>:<number>

2024-05-13 23:22:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道怎样才能打印出下面的清单

mylist=[['carrot', 10], ['potatoe', 8], ['apple', 23]]

按以下格式

<carrot>:<10>
<potatoe>:<8>
<apple>:<23>

Tags: apple格式carrotmylistpotatoe
2条回答

您可以使用一个简单的for循环,如下所示:

mylist = [['carrot', 10], ['potatoe', 8], ['apple', 23]]

for entry, quantity in mylist:
    print '<{}>:<{}>'.format(entry, quantity)

提供以下输出:

<carrot>:<10>
<potatoe>:<8>
<apple>:<23>

您可以轻松地迭代它并执行它。下面是一个示例实现

mystring = "\n".join(["<{0}>:<{1}>".format(*lst) for lst in mylist])
print(mystring)

相关问题 更多 >