gpt4 book ai didi

python - 在多维列表中追加项目

转载 作者:行者123 更新时间:2023-12-04 01:14:49 24 4
gpt4 key购买 nike

我不确定我正在尝试做的这件事情在 Python 中被称为什么,但是如何将项目添加到多维列表中?我知道如何对常规列表执行此操作,并且我试图弄清楚这个数组的内容但完全迷路了。

我想做这样的列表

portfolio_list =[
['TSLA',5000],
['BA',2000],
['MSFT',2000],
['AAPL',1500],
]

我在 while 循环中有这段代码

new_item = input("Add stock ticker > ").upper()
add_to_list(new_item) #adds stock ticker to list

new_value = input("What is value of {} > ".format(new_item))
add_item_value(new_value)

我对这些的定义是

def add_to_list(item): 
portfolio_list.append([[item]],axis=0)
print("{} has been added".format(item,))

def add_item_value(item):
portfolio_list.append([[item]],axis=1)
print("{} value has been added to {} ".format(item,new_item))

我得到的错误

Add stock ticker > tsla


Traceback (most recent call last):
File "test_effecient_frontier.py", line 139, in <module>
add_to_list(new_item) #adds stock ticker to list
File "test_effecient_frontier.py", line 70, in add_to_list
portfolio_list.append([[item]],axis=0)
TypeError: append() takes no keyword arguments

非常感谢任何帮助!

最佳答案

你可以

  1. 询问这两种信息
  2. append 新的子列表到主 list,不要忘记转换为 int
portfolio_list = [
['TSLA', 5000],
['BA', 2000],
['MSFT', 2000],
['AAPL', 1500],
]

new_item = input("Add stock ticker > ").upper()
new_value = input("What is value of {} > ".format(new_item))
portfolio_list.append([new_item, int(new_value)])

通过 while 循环,你可以有类似的想法

while True:
new_item = input("Add stock ticker > ").upper()
if new_item == "STOP":
break
new_value = input("What is value of {} > ".format(new_item))
portfolio_list.append([new_item, int(new_value)])

关于python - 在多维列表中追加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63692754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com