<p>Python内置了一些非常强大的语言构造。您可以从文件中读取行,如:</p>
<pre>
with open(name_of_file,"r") as file:
for line in file:
# process the line
</pre>
<p>可以使用<a href="http://docs.python.org/library/string.html#string.split" rel="nofollow noreferrer">string.split</a>函数沿逗号分隔行,也可以使用<a href="http://docs.python.org/library/string.html#string.strip" rel="nofollow noreferrer">string.strip</a>来消除中间的空白。Python有非常强大的<a href="http://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="nofollow noreferrer">lists</a>和<a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="nofollow noreferrer">dictionaries</a>。</p>
<p>要创建一个列表,只需使用像[]这样的空括号,而要创建一个空字典,则使用{}:</p>
<pre>
mylist = []; # Creates an empty list
mydict = {}; # Creates an empty dictionary
</pre>
<p>您可以使用.append()函数插入列表,而可以使用索引下标插入字典。例如,可以使用<code>mylist.append(5)</code>将5添加到列表中,而可以使用<code>mydict[key]=value</code>将键<code>key</code>与值<code>value</code>关联。要测试字典中是否存在密钥,可以使用<code>in</code>关键字。例如:</p>
<pre>
if key in mydict:
print "Present"
else:
print "Absent"
</pre>
<p>要遍历列表或字典的内容,只需使用for循环,如下所示:</p>
<pre>
for val in mylist:
# do something with val
for key in mydict:
# do something with key or with mydict[key]
</pre>
<p>由于在许多情况下,在遍历列表时必须同时具有值和索引,因此还有一个名为enumerate的内置函数,可以省去自己计算索引的麻烦:</p>
<pre>
for idx, val in enumerate(mylist):
# do something with val or with idx. Note that val=mylist[idx]
</pre>
<p>上述代码在功能上与以下代码相同:</p>
<pre>
idx=0
for val in mylist:
# process val, idx
idx += 1
</pre>
<p>如果您这样选择,您还可以在索引上迭代:</p>
<pre>
for idx in xrange(len(mylist)):
# Do something with idx and possibly mylist[idx]
</pre>
<p>此外,还可以使用<a href="http://docs.python.org/library/functions.html#len" rel="nofollow noreferrer">len</a>获取列表中的元素数或字典中的键数。</p>
<p>通过使用列表理解,可以对字典或列表的每个元素执行操作;但是,我建议您只使用for循环来完成该任务。但是,举个例子:</p>
<pre>
>>> list1 = range(10)
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list2 = [2*x for x in list1]
>>> list2
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
</pre>
<p>当你有时间的时候,我建议你阅读<a href="http://docs.python.org/tutorial/" rel="nofollow noreferrer">Python tutorial</a>来获得更深入的知识。</p>