【问题标题】:print the same values in a list of dicts on same line [closed]在同一行的字典列表中打印相同的值[关闭]
【发布时间】:2014-06-15 15:38:12
【问题描述】:

我有一个这样的字典列表:

mylist = [{'name':'Alice','age':18},{'name':'Bob','age':19}]

我想在一行中打印出来,如下所示:

Alice is 18 years old, Bob is 19 years old

如果我遍历它并使用 print 它总是使用换行符...

【问题讨论】:

  • 你应该看看 Python 的字符串方法,尤其是str.join

标签: python list dictionary printing


【解决方案1】:

不要使用 print 进行迭代,而是使用 join,如

print ", ".join([entry['name'] + " is " + str(entry['age']) + " years old" for entry in mylist])

join 将作为参数给出的列表中的字符串与调用它的任何字符串粘贴在一起。当然,您也可以将entry['name'] + " is " + str(entry['age']) + " years old" 替换为格式字符串,例如"%s is %d years old" % (entry['name'], entry['age'])" 或(使用新的格式字符串语法和关键字参数)"{name} is {age} years old".format(**entry)

【讨论】:

    【解决方案2】:

    你可以像这样使用 Python 字符串作为模板

    mylist = [{'name': 'Alice', 'age': 18}, {'name': 'Bob', 'age': 19}]
    print ", ".join("{name} is {age} years old".format(**item) for item in mylist)
    # Alice is 18 years old, Bob is 19 years old
    

    我们从列表中取出每一项并解压缩字符串上的字典以替换相应的值。最后,我们将结果与, 连接起来,这将以您期望的格式给出结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 2021-08-21
      • 2021-12-15
      • 2022-06-14
      相关资源
      最近更新 更多