我有一個 csv 文件,其中包含 3 列 x、y、z 坐標(biāo),即這種格式:我使用下面的代碼來導(dǎo)入它并處理它的數(shù)據(jù):import csvfrom operator import itemgettercsvfile = open(r'C:\Users\%username%\Desktop\Deep-lizard\x_y_z coor.csv')inFile = csv.reader(csvfile)# skip headerinFile.__next__()#Read and sort the vertices coordinates (sort by x and y)vertices = sorted( [(float(r[0]), float(r[1]), float(r[2])) for r in inFile], key = itemgetter(0,1) )這變成vertices了一個元組列表:我想要實現(xiàn)的是過濾列表,如果元組中的第三個元素(即 z 坐標(biāo))大于 0,則在列表中包含該條目(3 個元素的元組),否則如果它為 0,則不要不包括它。這樣做的最佳方法是什么?
1 回答

BIG陽
TA貢獻(xiàn)1859條經(jīng)驗 獲得超6個贊
您可以if在理解的末尾放置一個語句以進(jìn)行過濾。
In [1]: l = list(zip(range(10),range(0,20,2)))
...: l
...:
Out[1]:
[(0, 0),
(1, 2),
(2, 4),
(3, 6),
(4, 8),
(5, 10),
(6, 12),
(7, 14),
(8, 16),
(9, 18)]
In [2]: [x for x in l if x[1]<13]
Out[2]: [(0, 0), (1, 2), (2, 4), (3, 6), (4, 8), (5, 10), (6, 12)]
添加回答
舉報
0/150
提交
取消