【问题标题】:create list when if == ok in python在python中if == ok时创建列表
【发布时间】:2020-04-20 08:28:21
【问题描述】:

如果status"select",我想在list 中添加值,但它会用最后一个值覆盖list 中的值

if status == 'select':
    object_name = input("Enter a name for the tracked object:")
    Ax = x - w/2
    Ay = y - h/2
    p1 = (object_name,Ax,Ay)
    list = []
    list.append(p1)
    print(list)
    print(len(list))

【问题讨论】:

  • if status == 'select': (x, y, w, h) = [int(v) for v in box] object_name = input("输入被跟踪对象的名称:" ) Ax = x - w/2 Ay = y - h/2 p1 = (object_name,Ax,Ay) list = [] list.append(p1) print(list) print(len(list))
  • list = [] - 这会覆盖你的整个列表
  • @h4z3 从技术上讲,它不会“覆盖”任何内容,它只是将名称 list 重新绑定到一个新列表。如果您对原始列表有其他引用,则此列表不受影响。
  • @TiaNomena 不相关(参见 samthegolden 的回答),但您不应该使用内置类型名称作为变量名称 - 它会隐藏内置类型,并经常导致代码后期出现意外错误。

标签: python list if-statement


【解决方案1】:

每次进入if 范围时,您都会创建一个列表。之前创建它,这样它就不会覆盖其他更改。

list = []

...

if status == 'select':

            object_name = input("Enter a name for the tracked object:")
            Ax = x - w/2
            Ay = y - h/2
            p1 = (object_name,Ax,Ay)
            list.append(p1)


            print(list)
            print(len(list))

【讨论】:

  • 谢谢。我有另一个问题。如果我想比较 Ax 中的值在列表中的第一个值和 Ax 在列表中的第二个值中。我该如何进行?
  • 你可以使用索引。 if Ax == list[0] 用于第一个值,if Ax == list[1] 用于第二个值。
  • @TiaNomena 如果您还有其他问题,请在另一个问题中发布。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-06-20
  • 2018-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
相关资源
最近更新 更多