6个实例,8段代码,详解 Python 中的 For 循环

Python 支持for循环,它的语法与其他语言(如JavaScript 或Java)稍有不同。下面的代码块演示如何在Python中使用for循环来遍历列表中的元素:

上述的代码段是将三个字母分行打印的。你可以通过在print语句的后面添加逗号“,”将输出限制在同一行显示(如果指定打印的字符很多,则会“换行”),代码如下所示:

当你希望通过一行而不是多行显示文本中的内容时,可以使用上述形式的代码。Python还提供了内置函数reversed(),它可以反转循环的方向,例如:

注意,只有当对象的大小是确定的,或者对象实现了_reversed_()方法的时候反向遍历的功能才有效。

01 使用tryexcept的for循环

清单1 的StringToNums.py说明了如何对一组从字符串转换而来的整数求和。

  • 清单1 StringToNums.py
<ol >
line = '1 2 3 4 10e abc' 
sum  = 0 
invalidStr = "" 
print('String of numbers:',line) 
for str in line.split(" "): 
  try: 
    sum = sum + eval(str) 
  except: 
    invalidStr = invalidStr + str + ' ' 
print('sum:', sum) 
if(invalidStr != ""): 
  print('Invalid strings:',invalidStr) 
else: 
  print('All substrings are valid numbers') 

清单1首先初始化变量line、sum和invalidStr,然后显示line的内容。接下来将line中的内容分割为单词,然后通过try代码块逐个将单词的数值累加到变量sum中。如果发生异常,则将当前str的内容追加到变量invalidStr。

当循环执行结束,清单1 打印出数值单词的和,并在后面显示非数值单词。它的输出如下所示:

02 指数运算

清单2 的Nth_exponet.py说明了如何计算一组整数的幂。

  • 清单2 Nth_exponet.py
<ol >
maxPower = 4 
maxCount = 4 
def pwr(num): 
  prod = 1 
  for n in range(1,maxPower+1): 
    prod = prod*num 
    print(num,'to the power',n, 'equals',prod) 
  print('-----------') 
for num in range(1,maxCount+1): 
    pwr(num) 

清单2 中有一个pwr()函数,其参数为一个数值。此函数中的循环可打印出参数的1 到n次方,n的取值范围在1到maxCount+1之间。

代码的第二部分通过一个for循环调用pwr()函数从1到maxCount+1的值。它的输出如下所示:

03 嵌套的循环

清单3 的Triangular1.py说明了如何打印一行连续整数(从1开始),其中每一行的长度都比前一行大1。

  • 清单3 Triangular1.py
<ol >
max = 8 
for x in range(1,max+1): 
  for y in range(1,x+1): 
    print(y,'', end='') 
  print()  

清单3首先初始化max变量为8,之后通过变量x从1到max+1执行循环。内层循环有一个值为从1到x+1的循环变量y,并打印y的值。它的输出如下所示:

04 在for循环中使用split()函数

Python支持各种便捷的字符串操作相关函数,包括split()函数和join()函数。在需要将一行文本分词化(即“分割”)为单词,然后使用for循环遍历这些单词时,split()函数非常有用。

join()函数与split()函数相反,它将两个或多个单词“连接”为一行。通过使用split()函数,你可以轻松地删除句子中多余的空格,然后调用join()函数,使文本行中每个单词之间只有一个空格。

1. 使用split()函数做单词比较

清单4 的Compare2.py说明了如何通过split()函数将文本字符串中的每个单词与另一个单词进行比较。

  • 清单4 Compare2.py
<ol >
x = 'This is a string that contains abc and Abc' 
y = 'abc' 
identical = 0 
casematch = 0 
for w in x.split(): 
  if(w == y): 
    identical = identical + 1 
  elif (w.lower() == y.lower()): 
    casematch = casematch + 1 
if(identical > 0): 
 print('found identical matches:', identical) 
if(casematch > 0): 
 print('found case matches:', casematch) 
if(casematch == 0 and identical == 0): 
 print('no matches found') 

清单4 通过split()函数对字符串x中的每个单词与单词abc进行比较。如果单词精确匹配,就将identical变量加1;否则就尝试不区分大小写进行比较,若匹配就将casematch变量加1。

清单4 的输出如下所示:

2. 使用split()函数打印指定格式的文本

清单5 的FixedColumnCount1.py 说明了如何打印一组设定固定宽度的字符串。

  • 清单5 FixedColumnCount1.py
<ol >
import string 
wordCount = 0 
str1 = 'this is a string with a set of words in it' 
print('Left-justified strings:') 
print('-----------------------') 
for w in str1.split(): 
   print('%-10s' % w) 
   wordCount = wordCount + 1 
   if(wordCount % 2 == 0): 
      print("") 
print("n") 
print('Right-justified strings:')  
print('------------------------')  
wordCount = 0 
for w in str1.split(): 
   print('%10s' % w) 
   wordCount = wordCount + 1 
   if(wordCount % 2 == 0): 
      print() 

清单5 首先初始化变量wordCount和str1,然后执行两个for循环。第一个for循环对str1的每个单词进行左对齐打印,第二个for循环对str1的每个单词进行右对齐打印。在每个循环中当wordCount是偶数的时候就输出一次换行,这样每打印两个连续的单词之后就换行。清单5的输出如下所示:

3. 使用split()函数打印固定宽度的文本

清单6 的FixedColumnWidth1.py说明了如何打印固定宽度的文本。

  • 清单6 FixedColumnWidth1.py
<ol >
import string 
left = 0 
right = 0 
columnWidth = 8 
str1 = 'this is a string with a set of words in it and it will be split into a fixed column width' 
strLen = len(str1) 
print('Left-justified column:')  
print('----------------------')  
rowCount = int(strLen/columnWidth) 
for i in range(0,rowCount): 
   left  = i*columnWidth 
   right = (i+1)*columnWidth-1 
   word  = str1[left:right] 
   print("%-10s" % word) 
# check for a 'partial row' 
if(rowCount*columnWidth < strLen): 
   left  = rowCount*columnWidth-1; 
   right = strLen 
   word  = str1[left:right] 
   print("%-10s" % word) 

清单6初始化整型变量columnWidth和字符串类型变量str1。变量strLen是str1的长度,变量rowCount是strLen除以columnWidth的值。之后通过循环打印rowCount行,每行包含columnWidth个字符。代码的最后部分输出所有“剩余”的字符。清单6的输出如下所示:

4. 使用split()函数比较文本字符串

清单7 的CompareStrings1.py说明了如何判断一个文本字符串中的单词是否出现在另一个文本字符串中。

  • 清单7 CompareStrings1.py
<ol >
text1 = 'a b c d' 
text2 = 'a b c e d' 
if(text2.find(text1) >= 0): 
  print('text1 is a substring of text2') 
else: 
  print('text1 is not a substring of text2') 
subStr = True 
for w in text1.split(): 
  if(text2.find(w) == -1): 
    subStr = False 
    break 
if(subStr == True): 
  print('Every word in text1 is a word in text2') 
else: 
  print('Not every word in text1 is a word in text2') 

清单7 首先初始化两个字符串变量text1和text2,然后通过条件逻辑判断字符串text2是否包含了text1(并输出相应打印信息)。

清单7的后半部分通过一个循环遍历字符串text1中的每个单词,并判断其是否出现在text2中。如果发现有匹配失败的情况,就设置变量subStr为False,并通过break语句跳出循环,提前终止for循环的执行。最后根据变量subStr的值打印对应的信息。清单7的输出如下所示:

05 用基础的for循环显示字符串中的字符

清单8 的StringChars1.py说明了如何打印一个文本字符串中的字符。

  • 清单8 StringChars1.py
<ol >
text = 'abcdef' 
for ch in text: 
   print('char:',ch,'ord value:',ord(ch)) 
print 

清单8 的代码简单直接地通过一个for循环遍历字符串text并打印它的每个字符以及字符的ord值(ASCII 码)。清单8 的输出如下所示:

06 join()函数

另一个去掉多余空格的方法是使用join()函数,代码示例如下所示:

split()函数将一个文本字符串“分割”为一系列的单词,同时去掉多余的空格。接下来join()函数使用一个空格作为分隔符将字符串text1中的单词连接在一起。上述代码的最后部分使用字符串XYZ替换空格作为分隔符,执行相同的连接操作。上述代码的输出如下:

关于作者:奥斯瓦尔德·坎佩萨托(OswaldCampesato),专门研究深度学习、Java、Android和TensorFlow。他是25本书的作者/合著者。

本文摘编自《机器学习入门:Python语言实现》,经出版方授权发布。(ISBN:9787111695240)

以上就是6个实例,8段代码,详解 Python 中的 For 循环的详细内容,更多请关注https://www.sxiaw.com/其它相关文章!