Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python列表理解。编写此代码的其他/更好的方法?_Python_List Comprehension - Fatal编程技术网

Python列表理解。编写此代码的其他/更好的方法?

Python列表理解。编写此代码的其他/更好的方法?,python,list-comprehension,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 >

下面是我正在使用的一个示例:

    >>> 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')]

当直接从控制台工作时,这是一种很好的处理方法。如果我必须从一个.py文件运行这个呢。我想知道是否有一种高效/更好的方法来重新编写此文件,也许可以使用for循环?

您只需在一个步骤中生成最终输出:

final = [(y, x.lower()) for x, y in a]
或者使用更好的变量名,使其更清楚地显示在何处:

final = [(tag, word.lower()) for word, tag in a]
演示:


您只需在一个步骤中生成最终输出:

final = [(y, x.lower()) for x, y in a]
或者使用更好的变量名,使其更清楚地显示在何处:

final = [(tag, word.lower()) for word, tag in a]
演示:


您可以执行以下操作:

[(i[1], i[0].lower()) for i in a]

您可以执行以下操作:

[(i[1], i[0].lower()) for i in a]

对不起,我删除了我的评论而不是编辑它。无论如何,我读它的方式是错误的。谢谢。我明白。:)我想您最初的答案是:final=[(a[1].lower(),a[0].lower())表示a中的项],我的元组列表命名为“a”。这就是为什么我感到困惑,并问您是否正在对元组应用.lower()。但是谢谢你的新版本。很清楚。对不起,我删除了我的评论而不是编辑它。无论如何,我读它的方式是错误的。谢谢。我明白。:)我想您最初的答案是:final=[(a[1].lower(),a[0].lower())表示a中的项],我的元组列表命名为“a”。这就是为什么我感到困惑,并问您是否正在对元组应用.lower()。但是谢谢你的新版本。很清楚,很可爱!非常感谢你。我很明白:)可爱!非常感谢你。我很明白:)