Home >Backend Development >Python Tutorial >6 examples, 8 code snippets, detailed explanation of For loop in Python

6 examples, 8 code snippets, detailed explanation of For loop in Python

PHPz
PHPzforward
2023-04-11 19:43:172587browse

Python supports for loops, and its syntax is slightly different from other languages ​​(such as JavaScript or Java). The following code block demonstrates how to use a for loop in Python to iterate over the elements in a list:

The above code snippet separates three letters into rows Printed. You can limit the output to the same line by adding a comma "," after the print statement (if you specify a lot of characters to print, it will "wrap"), the code is as follows:

When you want to display the content in the text in one line instead of multiple lines, you can use the above form of code. Python also provides the built-in function reversed(), which can reverse the direction of the loop, for example:

Note that only when the size of the object is determined , or the reverse traversal function is only effective when the object implements the _reversed_() method.

01 A for loop using tryexcept

Listing 1's StringToNums.py illustrates how to sum a set of integers converted from strings.

  • Listing 1 StringToNums.py
<ol><pre class="brush:sql;toolbar:false;">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') 

Listing 1 first initializes the variables line, sum and invalidStr, and then displays the content of line. Next, the content in the line is divided into words, and then the values ​​of the words are accumulated into the variable sum one by one through the try code block. If an exception occurs, the contents of the current str are appended to the variable invalidStr.

When the loop execution ends, Listing 1 prints out the sum of the numeric words, and displays the non-numeric words after it. Its output looks like this:

02 Exponential Operations

Nth_exponet.py in Listing 2 illustrates how to calculate a set of integers of power.

  • Listing 2 Nth_exponet.py
<ol><pre class="brush:sql;toolbar:false;">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) 

There is a pwr() function in Listing 2, whose parameter is a numeric value. The loop in this function can print out the parameter raised to the power 1 to n, with n ranging from 1 to maxCount 1.

The second part of the code calls the pwr() function from 1 to maxCount 1 through a for loop. Its output looks like this:

03 Nested Loops

Listing 3 of Triangular1.py illustrates how to print a line Consecutive integers (starting at 1) where the length of each line is 1 greater than the previous line.

  • Listing 3 Triangular1.py
<ol><pre class="brush:sql;toolbar:false;">max = 8 
for x in range(1,max+1): 
  for y in range(1,x+1): 
    print(y,'', end='') 
  print()  

Listing 3 first initializes the max variable to 8, and then executes a loop through the variable x from 1 to max 1 . The inner loop has a loop variable y with a value from 1 to x 1, and prints the value of y. Its output is as follows:

04 Use the split() function in a for loop

Python supports various convenient String operation related functions, including split() function and join() function. The split() function is useful when you need to tokenize (i.e., "split") a line of text into words and then use a for loop to iterate through the words.

The join() function is the opposite of the split() function, which "joins" two or more words into one line. You can easily remove extra spaces in a sentence by using the split() function and then calling the join() function so that there is only one space between each word in the text line.

1. Use the split() function for word comparison

Compare2.py in Listing 4 illustrates how to compare each word in a text string with another word using the split() function Compare.

  • Listing 4 Compare2.py
<ol><pre class="brush:sql;toolbar:false;">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') 

Listing 4 uses the split() function to compare each word in the string x with the word abc Compare. If the words match exactly, the identical variable is incremented by 1; otherwise, a case-insensitive comparison is attempted, and if there is a match, the casematch variable is incremented.

The output of Listing 4 is as follows:

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

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

  • 清单5 FixedColumnCount1.py
<ol><pre class="brush:sql;toolbar:false;">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><pre class="brush:sql;toolbar:false;">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><pre class="brush:sql;toolbar:false;">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><pre class="brush:sql;toolbar:false;">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)

 

The above is the detailed content of 6 examples, 8 code snippets, detailed explanation of For loop in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete