Python:遍历字符串和列表

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python:遍历字符串和列表相关的知识,希望对你有一定的参考价值。

  1. ## The first example uses a string as the sequence to create a list of characters in the string:
  2.  
  3. >>>word = "Python"
  4. >>>list = []
  5. >>>for ch in word:
  6. >>> list.append(ch)
  7. >>>print list
  8. ['P', 'y', 't', 'h', 'o', 'n']
  9.  
  10.  
  11. ## This example uses the range() function to create a temporary sequence of integers the size of a list so the items in the list can be added to a string in order:
  12.  
  13. >>>string = ""
  14. >>>for i in range(len(list)):
  15. >>> string += list[i]
  16. >>>print string
  17. Python
  18.  
  19.  
  20.  
  21. ## This example uses the enumerate(string) function to create a temporary sequence. The enumerate function returns the enumeration in the form of (0, s[0]), (1, s[1]), and so on, until the end of the sequence string, so the for loop can assign both the i and ch value for each iteration to create a dictionary:
  22.  
  23. >>>dict = {}
  24. >>>for i,ch in enumerate(string):
  25. >>> dict[i] = ch
  26. >>>print dict
  27. {0: 'P', 1: 'y', 2: 't', 3: 'h', 4: 'o', 5: 'n'}
  28.  
  29.  
  30.  
  31. ## This example uses a dictionary as the sequence to display the dictionary contents:
  32.  
  33. >>>for key in dict:
  34. >>> print key, '=', dict[key]
  35. 0 = P
  36. 1 = y
  37. 2 = t
  38. 3 = h
  39. 4 = o
  40. 5 = n

以上是关于Python:遍历字符串和列表的主要内容,如果未能解决你的问题,请参考以下文章

python中列表的遍历

动态循环遍历Python函数中的函数列表

Python3基础 for循环 遍历并输出一个字符串的列表

Python TypeError 遍历列表

Python for-in Loop常见遍历方法

python中for循环的用法