Printing within list comprehension in Python

2019-07-04 19:53发布

问题:

I am getting a syntax error when executing the following code. I want to print within a list comprehension. As you see, I tried a different approach (commented out line) by using print(). But I think this syntax is supported in Python 3 as earlier versions of Python treat print as a statement.

  1 import sys
  2 import nltk
  3 import csv
  4 from prettytable import PrettyTable
  5 CSV_FILE = sys.argv[1]
  6 # Handle any known abbreviations, # strip off common suffixes, etc.
  7 transforms = [(', Inc.', ''), (', Inc', ''), (', LLC', ''), (', LLP', '')]
  8 csvReader = csv.DictReader(open(CSV_FILE), delimiter=',', quotechar='"')
  9 contacts = [row for row in csvReader]
 10 companies = [c['Company'].strip() for c in contacts if c['Company'].strip() != '']
 11 for i in range(len(companies)):
 12     for transform in transforms:
 13         companies[i] = companies[i].replace(*transform)
 14 #fields=['Company', 'Freq']
 15 #pt = PrettyTable(fields=fields)
 16 #pt.set_field_align('Company', 'l')
 17 fdist = nltk.FreqDist(companies)
 18 #[pt.add_row([company, freq]) for (company, freq) in fdist.items() if freq > 1] 
 19 #[print("["+company+","+freq+"]") for (company, freq) in fdist.items() if freq > 1] 
 20 [print company for (company, freq) in fdist.items() if freq > 1]
 21 #pt.printt()
~                                           

回答1:

No statements can appear in Python expressions. print is one kind of statement in Python 2, and list comprehensions are one kind of expression. Impossible. Neither can you, for example, put a global statement in an index expression.

Note that in Python 2, you can put

from __future__ import print_function

to have print() treated as a function instead (as it is in Python 3).



回答2:

It's not a print statement in Python 3, it's a function.

>>> sys.version
'3.4.0a4+ (default:8af2dc11464f, Nov 12 2013, 22:38:21) \n[GCC 4.7.3]'
>>> [print(i) for i in range(4)]
0
1
2
3

and returns:

[None, None, None, None]

And as Tim Peters said, no statements can be in comprehensions or generator expressions.



回答3:

The other answer is: Don't do this. Use a for loop. There's no need to materialize a list of None's in memory. The print function returns None, and the printing is a mere side-effect from the perspective of functional programming. If you need the printing, use a for-loop, since there's no need to materialize a list in memory. If you need the list of None's, use None, not print(i), since this would make your program IO bound.

If you need both, do them so that you can easily remove the one you don't need when you are done.