如何为此代码添加较低的功能

时间:2011-12-09 06:01:35

标签: python

我想以小写字母打印输出,但是我得不到正确的结果。这是我的代码。请帮忙!

import csv
mags = csv.reader(open("mags.csv","rU"))

for row in mags:


     print [row[index] for index in (1, 0)]

     print [item.lower( ) for item in row]

3 个答案:

答案 0 :(得分:2)

列表理解可以嵌套,就像这样

print [item.lower() for item in [row[index] for index in (1, 0)]]

没有一个口译员可以方便地测试这个,等等。

答案 1 :(得分:1)

你确定这行是一个字符串列表吗? 我看到正确的输出:

>>> row = [ "alpA", "bETA","gammA" ]
>>> print [item.lower( ) for item in row]
['alpa', 'beta', 'gamma']
>>>

答案 2 :(得分:1)

你可以嵌套这样的两种理解:

print [item.lower() for item in [row[index] for index in (1, 0)]]

这样你就可以使用第一次理解中的数据(这个顺序中第二行和第一项)作为第二项的输入(小写所有内容)。

您也可以对行进行切片,而不是使用对第一行的理解:

 print [item.lower() for item in row[::-1][-2:]] # Slicing in 2 steps: [::-1] reverses the list and [-2:] returns the last two items of the reversed list

或(更短,但反向索引切片不能像你想象的那样工作)

 print [item.lower() for item in row[1::-1] # Same thing, but it helps to break these things up into steps