如何在Python中声明和添加项目到数组?
我正在尝试将项目添加到python中的数组.
I'm trying to add items to an array in python.
我跑步
array = {}
然后,我尝试通过以下操作向此数组添加一些内容:
Then, I try to add something to this array by doing:
array.append(valueToBeInserted)
似乎没有.append
方法.如何将项目添加到数组?
There doesn't seem to be a .append
method for this. How do I add items to an array?
{}
代表空字典,而不是数组/列表.对于列表或数组,您需要[]
.
{}
represents an empty dictionary, not an array/list. For lists or arrays, you need []
.
要初始化一个空列表,请执行以下操作:
To initialize an empty list do this:
my_list = []
或
my_list = list()
要将元素添加到列表中,请使用append
To add elements to the list, use append
my_list.append(12)
要extend
列表以包含另一个列表中的元素,请使用extend
To extend
the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
要从列表中删除元素,请使用remove
To remove an element from a list use remove
my_list.remove(2)
字典表示键/值对的集合,也称为关联数组或映射.
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
要初始化空字典,请使用{}
或dict()
To initialize an empty dictionary use {}
or dict()
字典具有键和值
my_dict = {'key':'value', 'another_key' : 0}
要使用其他词典的内容扩展词典,可以使用update
方法
To extend a dictionary with the contents of another dictionary you may use the update
method
my_dict.update({'third_key' : 1})
要从字典中删除值
del my_dict['key']