簡體   English   中英

如何從集合中的(x,y)坐標返回x值

[英]How to return x value from (x,y) coordinates in a set

def has_x_value(cs,x):
      tuple_convert = list(cs)
      x_values = [x[0] for x in tuple_convert]
      for i in x_values:
         if i == x:
             return True
         else:
             return False
a = has_x_value({(2,4), (1,5), (6,3), (2,2)},2)
b = has_x_value({(14,14), (13,9), (13,16), (10,12)},10)
print(a)
print(b)

我正在嘗試制作一個 function 如果集合包含 x 坐標則返回 True,否則返回 False。 我寫了上面的代碼,但是它對a返回True,對b返回False,但我不明白為什么它對b返回False。

因為您在循環的兩個分支中都return ,所以您當前的代碼相當於:

def has_x_value(cs, x):
    tuple_convert = list(cs)
    x_values = [x[0] for x in tuple_convert]
    if x_values[0] == x:
        return True
    else:
        return False

如您所見,您只檢查第一個坐標。

只有在沒有找到坐標的情況下才需要return False

def has_x_value(cs, x):
    x_values = [x[0] for x in cs]
    for i in x_values:
        if i == x:
            return True
    return False

然后可以將其轉換為更簡單的:

def has_x_value(cs, x):
    x_values = [x[0] for x in cs]

    return x in x_values

甚至只是:

def has_x_value(cs, x):
    return any(x == coord[0] for coord in cs)

  • 請注意, tuple_convert不是必需的,您可以對集合進行相同的迭代。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM