For循环赋值
前提条件:我创建了一个road类,这个类里面有这些属性。我先初始化给road赋值,然后再把这些对象放到roadObjList集合里面。
目标:从roadObjList集合里面取出每个road对象的objectid值,然后放入到新的列表里面。
class road(): def __init__(self,gid,objectid,name,width,direction,speed,type,snode,enode,length,startX,startY,endX,endY): self.gid= gid self.objectid = objectid self.name = name self.width = width self.direction = direction self.speed = speed self.type = type self.snode = snode self.enode = enode self.length = length self.startX = startX self.startY = startY self.endX = endX self.endY = endY
写法一:
objList = [] for r in roadObjList: objList.append(r.objectid)
写法二:
objList = [r.objectid for r in roadObjList]
我补充几句
关于for循环遍历的写法,还有好几种,虽然写法很low,但是效果都是差不多的。
写法一:
for i,ele in enumerate(roadPointObjList): print(i) print(ele)
写法二:
for i in range(0, len(roadPointObjList)): print(i) print(roadPointObjList[i])
for循环给列表赋值的简单写法
list1=[1,2,3,4]
将list1赋值给list2
list2=[a for a in list1]
list1+list2的值赋给list3,可以如下写代码:
list3=[x+y for x in list1 for y in list2]
多元数组赋值
x=[[1,2],[3,4],] y=[[1,2],[3,4],] z = [[i+g,j+h] for (i,j) in x for(g,h)in y] print(z)
输出结果:[[2, 4], [4, 6], [4, 6], [6, 8]]
x=[[1,2],[3,4],] y=[[1,2],[3,4],] z = [i+g+j+h for (i,j) in x for(g,h)in y] print(z)
输出结果:[6, 10, 10, 14]
下一篇: 单页面网站有何优势?如何优化单页面?
上一篇:python中input函数怎么使用?
评论