我正在尝试在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”对象不可订阅等错误。
答案 0 :(得分:0)
我认为这样做你想要的,虽然不清楚,因为你没有发布预期的结果......
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]]
您将新列表插入外部列表,而(我认为)您真正想要做的是替换值内部列表。