这也可以缩短为:
stopwords = ['to', 'a', 'for', 'by', 'an', 'am', 'the', 'so', 'it', 'and', 'The']
sent = "The water earth and air are vital"
acro = '. '.join(word[:2].upper() for word in sent.split() if word not in stopwords)
print(acro)
输出:
WA. EA. AI. AR. VI
更新:
但是,正如“mad”所指出的,
join
在这种情况下,希望创建一个字符串,首先是正确的长度,然后是正确的内容。但要知道正确的长度,它需要找到它要连接的所有组件的长度,因此,如果有一个列表作为其参数,则意味着它有一个大小,而我对生成器的原始答案只有在用完后才有大小。
所以,最好是:
acro = '. '.join([word[:2].upper() for word in sent.split() if word not in stopwords])