简体   繁体   English

在 Python 中打印元组列表会导致 [None,None,None]

[英]Printing a list of Tuples in Python results in [None,None,None]

I have a list of Tuples that I want to print in Jupyter Notebooks.我有一个要在 Jupyter Notebooks 中打印的元组列表。 My code prints them correctly but seems to be printing a strange line at the end '[None,None,None]', I can't figure out why.我的代码正确打印了它们,但似乎在末尾打印了一条奇怪的行“[None,None,None]”,我不知道为什么。

If I swap the list comprehension code with a for loop to print the same thing I don't get the '[None,None,None]' line.如果我用 for 循环交换列表理解代码以打印相同的内容,我不会得到 '[None,None,None]' 行。 But I'm trying to write more easy to read code and would prefer to keep the list comprehension approach, there is definitely something I can learn from this mistake.但是我正在尝试编写更易于阅读的代码,并且更愿意保留列表理解方法,我肯定可以从这个错误中学到一些东西。

Check error message and code in the attached image检查附加图像中的错误消息和代码

a = [(1, 108460.7476635514), (2, 103072.89682539682), (3, 77251.9265944645)]
[print('Group=', x[0], '; Avg=', x[1]) for x in a]

Jupyter notebooks return the value of the last variable in a code cell if there is no assignment operator (=) in the last statement.如果最后一个语句中没有赋值运算符 (=),Jupyter 笔记本将返回代码单元中最后一个变量的值。 This code outputs the value of the list (the return value of all print statements, or None) because you're creating a list during list comprehension.此代码输出列表的值(所有打印语句的返回值,或无),因为您在列表理解期间创建了一个列表。 Generally, it is bad practice to use list comprehension if you're not going to use the list it generates.通常,如果您不打算使用它生成的列表,那么使用列表推导是不好的做法。 The cleaner, more Pythonic way to do this is via a standard for loop:更简洁、更 Pythonic 的方法是通过标准 for 循环:

a = [(1, 108460.7476635514), (2, 103072.89682539682), (3, 77251.9265944645)]
for i in a:
    print('Group=', x[0], '; Avg=', x[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM