如何在 Python 中向数组声明和添加项目? [英] How to declare and add items to an array in Python?

查看:24
本文介绍了如何在 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']

这篇关于如何在 Python 中向数组声明和添加项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆