python3_ for循环

1、列表迭代

import serial  # 串口操作的方法和属性
import serial.tools.list_ports    #查找串口

comlist = serial.tools.list_ports.comports()   #为所有的串口分别生成ListPortInfo object,列表封装
print(comlist)
i = 0
#for i in range(len(comlist)):  #报错TypeError: 'int' object is not iterable
for i in int(len(comlist)):  #正常
    print(comlist[i])
# print(comlist.device)
connected = []
for element in comlist:
    connected.append(element.device)   #connected.append()在connected[]列表的后面追加
print("Connected COM ports: " + str(connected))
解释:不能直接用int进行迭代,而必须加个range
posted @ 2022-01-25 13:41  小鱼小鱼hi  阅读(70)  评论(0编辑  收藏  举报