我有一个列表,其中包含负值的元组,如此
vect=[(-x*3,-y*2) for x in [2,3,4] for y in [1,5,6]]
我希望打印列表的绝对值,如
[(6, 2), (6, 10), (6, 12), (9, 2), (9, 10), (9, 12), (12, 2), (12, 10), (12, 12)]
但是我试图获得输出但是出现了错误
TypeError:abs()的错误操作数类型:'tuple'
所以我需要有关此问题的帮助或建议。
答案 0 :(得分:1)
使用map
<强>实施例强>
vect=[(-x*3,-y*2) for x in [2,3,4] for y in [1,5,6]]
print([map(abs, i) for i in vect]) #Python3 --> print([list(map(abs, i)) for i in vect])
<强>输出:强>
[[6, 2], [6, 10], [6, 12], [9, 2], [9, 10], [9, 12], [12, 2], [12, 10], [12, 12]]
答案 1 :(得分:1)
使用简单的list comprehension:
[(abs(i[0]), abs(i[1])) for i in vect]
# [(6, 2), (6, 10), (6, 12), (9, 2), (9, 10), (9, 12), (12, 2), (12, 10), (12, 12)]