在Python中的列表理解中打印 [英] Printing within list comprehension in Python
问题描述
我想在列表理解中打印。
正如你所看到的,我通过使用print()尝试了一种不同的方法(注释掉了行)。但我认为Python 3支持这种语法,因为早期版本的Python将print作为语句。
1 import sys
2 import nltk
3 import csv
4从prettytable import PrettyTable
5 CSV_FILE = sys.argv [1]
6#处理任何已知的缩写,#strip off common suffixes (',Inc.',''),(',Inc',''),(',LLC',''),(',LLP','')等
7转换。 )]
8 csvReader = csv.DictReader(open(CSV_FILE),delimiter =',',quotechar ='''')
9个联系人= [在csvReader中行的行数]
10家公司= [c ['Company']。strip()for c in contacts if c ['Company']。strip()!='']
11 for range in(len(companies)):
12转换转换:
13家公司[i] =公司[i] .replace(*转换)
14 #fields = ['公司','频率']
15 #pt = PrettyTable(fields = fields)
16#pt.set_field_align('Company','l')
17 fd ftist.items()中的(公司,频率)ift = nltk.FreqDist(公司)
18#[pt.add_row([company,freq])如果freq> 1]
19#[print([+ + company +,+ freq +])for(company,freq)in fdist.items()if freq> 1]
20 [打印公司为(company,freq)在fdist.items()如果freq> 1]
21#pt.printt()
〜
没有语句可以出现在Python表达式中。 print 是Python 2中的一种语句,列表推导是一种表达式。不可能。例如,你也不能在索引表达式中放置
全局
语句。
import print_function
将 print()
作为一个函数对待(就像在Python 3中一样)。
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()
~
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).
这篇关于在Python中的列表理解中打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!