在列表中的元组中测试和访问值?

时间:2018-03-05 13:22:04

标签: python

我正在对列表推导进行一些练习,在这一个中,y坐标需要限制为0 <= y <= 10,我知道这根本不起作用,但我可以&#39 ; t让我的头围在列表中的元组以及如何访问元组的第二部分以便测试它

  xvals = [x for x in range(-5,5)]
  yvals = [(x**2)+5 for x in xvals]
  coords = list(zip(xvals, yvals))
  limitedcoords = [i for i in coords if ((j in i) <= 10)]
  print(limitedcoords)

感谢您的帮助!

3 个答案:

答案 0 :(得分:0)

您可能正在寻找与filter()功能相结合的lambda

xvals = [x for x in range(-5,5)]
yvals = [(x**2)+5 for x in xvals]
coords = list(zip(xvals, yvals))

print(coords)

limitedcoords = list(filter(lambda x: x[1] <= 10, coords))
print(limitedcoords)

这会产生

[(-5, 30), (-4, 21), (-3, 14), (-2, 9), (-1, 6), (0, 5), (1, 6), (2, 9), (3, 14), (4, 21)]
[(-2, 9), (-1, 6), (0, 5), (1, 6), (2, 9)]

此处,coords在第二个坐标x[1]上进行过滤。

<小时/> 另一种选择是

limitedcoords = [(x,y) for x,y in coords if 0 <= y <= 10]
print(limitedcoords)

产生相同的结果并且可能更快。

答案 1 :(得分:0)

限制y并在010之间绑定它可以实现如下:

limitedcoords = [(x, min(max(0, y), 10)) for x, y in coords]

产生:

[(-5, 10), (-4, 10), (-3, 10), (-2, 9), (-1, 6), (0, 5), (1, 6), (2, 9), (3, 10), (4, 10)]

没有min(max(0, y), 10)部分,你会得到:

[(-5, 30), (-4, 21), (-3, 14), (-2, 9), (-1, 6), (0, 5), (1, 6), (2, 9), (3, 14), (4, 21)]

注意第一个元组的30 y-coord如何变为10,依此类推。最后,使用0作为下限是没有意义的,因为 math 已经涵盖了这一点(x**2如果我们正在谈论,则不能<0实数)因此无需检查。

min(max(0, y), 10)如何运作:

从内到外阅读,我们实际上在说:

  1. max 0y(让我们称之为temp
  2. 获取mintemp的{​​{1}}。
  3. 伪代码中的示例:

    10

答案 2 :(得分:0)

这更像是一种风格+表现点。 [有关修复算法的详细信息,请参阅@Jan / @Ev.Kounis的解决方案。]

range()zip()等功能以及()内的理解所表示的生成器表达式的好处是它们都是懒惰的。为了提高效率,在实际需要计算之前,通常是最优的。

以下是一个如何重写算法的示例:

xvals = range(-5, 5)
yvals = ((x**2)+5 for x in xvals)
coords = zip(xvals, yvals)

limitedcoords = [(x, y) for x, y in coords if y <= 10]
# [(-2, 9), (-1, 6), (0, 5), (1, 6), (2, 9)]