【问题标题】:How to print list by using format function如何使用格式功能打印列表
【发布时间】:2019-08-15 00:35:49
【问题描述】:

我从 JAVA 转换而来,在 python 中很新。我知道 python 是一种方便的语言。然后我考虑是否可以在 print(''.format()) 函数中使用一种方法来打印一个列表,我在值之间插入几个单词。

我已经尝试过 print(''.format(for i in list)) 如下所示的简单示例:

movies.append(1)
movies.append('The Shawshank Redemption')
movies.append('5 star')
movies.append('whatever')
movies.append('www.google.com')
print('''
    The NO.{} Movie is :{}
    Rating:{}
    Quote:{}
    Link:{}
    '''.formate(for i in movie)

当然,它在最后一条语句中显示错误无效语法。

【问题讨论】:

  • 列表不是这里理想的数据结构,如果有字典的话会更好。 movies = [{'title': 'The Shawshank Redemption', 'rating': '5 star', 'quote':'whatever', 'link': 'www.google.com'}]您没有正确使用 .format() 。它用于使用输入参数列表格式化单个字符串。您可以在循环中使用它,但不能作为循环使用。
  • .format(*movie)
  • 语法错误是你缺少右括号)(也是format而不是formate
  • @juanpa.arrivillaga 好电话,忘记了列表拆包操作员。这在这里会很好用。
  • @campellcl 还是不错的评论。你提醒我在这种情况下使用字典。thx

标签: python list printing format


【解决方案1】:

for i in movies 是一个 for 语句,所以它期望有一个代码块。

你想要的是获取电影中的每个项目,然后将每个项目传递给函数,所以你应该这样做

print('''
    The NO.{} Movie is :{}
    Rating:{}
    Quote:{}
    Link:{}
    '''.format(*(i for i in movie)) # '*' unpacks the generator, so instead of passing a whole object to the function, you pass every object in the generator as an argument

请注意,您实际上可以像这样将解压列表传递给format

print('''
    The NO.{} Movie is :{}
    Rating:{}
    Quote:{}
    Link:{}
    '''.format(*movies) # '*' unpacks the generator, so instead of passing a whole object to the function, you pass every object in the generator as an argument

【讨论】:

    【解决方案2】:

    *moviesunpack argument lists

    movies = []
    movies.append(1)
    movies.append('The Shawshank Redemption')
    movies.append('5 star')
    movies.append('whatever')
    movies.append('www.google.com')
    print('The NO.{}\nMovie is :{}\nRating:{}\nQuote:{}\nLink:{} '.format(*movies))
    

    输出是

    The NO.1
    Movie is :The Shawshank Redemption
    Rating:5 star
    Quote:whatever
    Link:www.google.com 
    

    【讨论】:

    • 你也是对的。但我只能接受一个。 :( 无论如何谢谢
    猜你喜欢
    • 2021-09-18
    • 2012-09-15
    • 1970-01-01
    • 2020-07-25
    • 2016-07-20
    • 2020-11-22
    • 2017-01-25
    • 2014-12-11
    • 1970-01-01
    相关资源
    最近更新 更多