官术网_书友最值得收藏!

  • Practical Data Wrangling
  • Allan Visochek
  • 376字
  • 2021-07-02 15:16:10

Arrays (lists, if you ask Python)

An array is an ordered collection of values. Each item in an array is called an element. In Python, there can be an indefinite number of elements in an array. Python has a special name for its implementation of arrays, called a list. With regard to Python, I will use both words to refer to the same thing.

The following syntax can be used to create an array:

<arrayName>=[<element1>,<element2>,<element3>,...]

Inside square brackets, each element in the array is listed, separated by commas:

>> myArray = ["foo","bar","sup?","yo!"]
>> print(myArray)

The elements of an array can be accessed by their relative position, or index, in the array. To access an element of an array, you can use the following syntax:

>> <arrayName>[<index>]

For example:

>> print(myArray[0])
>> thirdElement = myArray[2]
>> print(thirdElement)

You may have noticed that the index of the third element of the array is 2, and not 3. This is because indexing starts with zero in Python and many other languages. This can be a bit confusing when starting out. When indexing arrays, be sure to access the nth element of an array using the number, n-1. Also notice that the index of the array has an integer data type. If you try to access an array with a float value, it will cause an error even if it represents an integer number (that is, 1.0).

You can also set the value of a particular element of an array by assigning a value to its index. The following line will set the first element of myArray to the string, I'm a new value:

>> myArray[0] = "I'm a new value"
>> print myArray[0]

You can only access or set a value of an array if the index belongs to the array. The following two lines will generate an error, because the array only has four elements, so its maximum index is three (for the fourth element):

>> myArray[6]
>> myArray[4]

Arrays are useful to represent grouped collections of data like a row in a spreadsheet. By keeping track of a set of data items in an ordered list, it is possible to easily store and retrieve items from a grouped collection of data.

主站蜘蛛池模板: 新宁县| 乌兰县| 温宿县| 洛扎县| 宣汉县| 托克托县| 海丰县| 内江市| 扬州市| 慈利县| 平武县| 阿拉尔市| 色达县| 新乡县| 和平区| 黔南| 新蔡县| 吴桥县| 邵东县| 平顺县| 富源县| 定远县| 克拉玛依市| 中超| 巴塘县| 大姚县| 松原市| 阳信县| 曲松县| 蓝田县| 南皮县| 宁武县| 和龙市| 濮阳市| 漳平市| 惠东县| 丹棱县| 会宁县| 烟台市| 通海县| 马关县|