我在python中有一个元组列表:
示例:
lstA = [ (12,0,20,50), (30,70,80,15), (11,12,0,35), (7,6,5,4), (1,0,0,4) ]
我想要在原始列表元组中将零值移除的输出。 因此,对于上述输入,输出应为:
lstA = [(12,20,50), (30,70,80,15), (11,12,35), (7,6,5,4), (1,4)]
如何以pythonic方式执行此操作?
答案 0 :(得分:4)
您可以通过列表压缩将它们传递出去,并在创建新元组时使用它们:
# read file and split by newlines (get list of rows)
with open('input.csv', 'r') as f:
rows = f.read().split('\n')
# loop over rows and append to list if they contain 'canada'
rows_containing_keyword = [row for row in rows if 'canada' in row]
# create and write lines to output file
with open('output.csv', 'w+') as f:
f.write('\n'.join(rows_containing_keyword))
答案 1 :(得分:1)
如果您熟悉其他编程语言中的filter
和lambda
,尽管它不像pythonic,您可能更喜欢这样的东西:
>>> original_tuples = [(12, 0, 20, 50), (30, 70, 80, 15), (11, 12, 0, 35), (7, 6, 5, 4), (1, 0, 0, 4)]
>>> tuples_without_zero = [tuple(filter(lambda x: x != 0, t)) for t in original_tuples]
>>> tuples_without_zero
[(12, 20, 50), (30, 70, 80, 15), (11, 12, 35), (7, 6, 5, 4), (1, 4)]