nic*_*cki 0 python list-comprehension
这是我正在使用的一个例子:
>>> a = [('The','det'),('beautiful','adj')]
>>> d = [y for (x,y) in a]
>>> z = [x.lower() for (x,y) in a]
>>> final=[]
>>> final = zip(d,z)
>>> final
>>> [('det', 'the'), ('adj', 'beautiful')]
Run Code Online (Sandbox Code Playgroud)
这是直接从控制台工作时使用的好方法.如果我必须从.py文件运行它会怎么样?我想知道是否有一种有效/更好的方法来重写它,也许使用for循环?
您只需一步即可生成最终输出:
final = [(y, x.lower()) for x, y in a]
Run Code Online (Sandbox Code Playgroud)
或使用更好的变量名称使其更清楚地放在哪里:
final = [(tag, word.lower()) for word, tag in a]
Run Code Online (Sandbox Code Playgroud)
演示:
>>> a = [('The','det'),('beautiful','adj')]
>>> [(y, x.lower()) for x, y in a]
[('det', 'the'), ('adj', 'beautiful')]
Run Code Online (Sandbox Code Playgroud)