【问题标题】:Append specific number to specific position in 2D list将特定数字附加到 2D 列表中的特定位置
【发布时间】:2018-05-24 09:26:28
【问题描述】:

我正在尝试在 2D 列表中的特定位置附加一个数字和另一个数字。

# Create UAS database list that was displayed in the file
uas_Stock = [["CS116",1],["CS117",1],["CS118",1],["CS119",1],["CS120",1]]

# Ask user to select which UAV they want to check out.
uas_out = input("Which UAV would you like to checkout? ")

# Append stock list to show UAS is checked out
if uas_out == "CS116":
    uas_Stock.insert(0, [0])
elif uas_out == "CS117":
    uas_Stock.insert(1, [0])
elif uas_out == "CS118":
    uas_Stock.insert(2, [0])
elif uas_out == "CS119":
    uas_Stock.insert(3, [0])
elif uas_out == "CS120":
    uas_Stock.insert(4, [0])
else:
    print("That input is not a valid UAS ID in our system.")

假设我选择 CS117,它将通过 if/else 语句运行到 CS117。然后它将在 uas_Stock 列表中当前 1 的位置插入 0。

它改为将 0 插入列表的 CS117 部分而不是 1 部分。我已经尝试过其他方法来做到这一点,但得到像“int”object not subscriptable之类的错误。

【问题讨论】:

    标签: python-3.x list insert insert-update


    【解决方案1】:

    我认为这可以满足您的要求,但由于您没有发布预期的结果而不清楚...

    uas_Stock = [["CS116",1],["CS117",1],["CS118",1],["CS119",1],["CS120",1]]
    
    # Ask user to select which UAV they want to check out.
    uas_out = input("Which UAV would you like to checkout? ")
    
    # Append stock list to show UAS is checked out
    found = False
    for stock_list in uas_Stock:
        if stock_list[0] == uas_out:
            stock_list[1] = 0
            found = True
            break
    if not found:
        print("That input is not a valid UAS ID in our system.")
    

    这会搜索列表并在找到 UAS 时将数字更改为 0。

    示例运行:

    Which UAV would you like to checkout? CS117
    >>> print(uas_Stock)
    [['CS116', 1], ['CS117', 0], ['CS118', 1], ['CS119', 1], ['CS120', 1]]
    

    您将新列表 插入外部 列表中,而(我认为)您真正想要做的是 替换 中的值内部列表。

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      相关资源
      最近更新 更多