Iterating over a list in python using for-loop

一个人想着一个人 提交于 2020-05-24 04:55:05

问题


I have a question about iterating over a list in python. Let's say I have a list: row = ['1', '2', '3'] and want to convert its element to integers, so that: row = [1, 2, 3].

I know I can do it with list comprehension:

row = [int(i) for i in row]

or for-loop:

for i in range(len(row)):
    row[i] = int(row[i])

My question concerns range(len(row)) part. Can someone answer in layman friendly way, why I can do something like this:

for i in row:
    print(i)

But I can't do this:

for i in row:
    row[i] = int(row[i])

回答1:


When you do for i in row, i takes the values in row, i.e. '1', then '2', then '3'.

Those are strings, which are not valid as a list index. A list index should be an integer. When doing range(len(row)) you loop on integers up to the size of the list.

By the way, a better approach is:

for elt_id, elt in enumerate(list):
    # do stuff



回答2:


When you do

for i in row:
    row[i] = int(row[int(i)]) 

i is the element in the array row. Therefore, i will be '1' then '2' then '3'.

But indexes have to be integers and i is a string so there will be an error.


If you do:

for i in row:
    row[int(i)] = int(row[i]) 

It will still be an error because i is the integer of element in the array row. Therefore, i will be 1 then 2 then 3.

But row[3] will cause a IndexError because there are only 3 elements in the list and numbering starts from 0.


While in the other case(the first case), i becomes 0 then 1 then 2 which does not cause an error because row[2] is valid.


The reason is :

range() is 0-index based, meaning list indexes start at 0, not 1. eg. The syntax to access the first element of a list is mylist[0] . Therefore the last integer generated by range() is up to, but not including, stop .




回答3:


Here's an example from IDLE:

>>> row = ['1', '2', '3']
>>> for i in row:
    row[i] = int(row[i])

Traceback (most recent call last):
  File "<pyshell#3>", line 2, in <module>
    row[i] = int(row[i])
TypeError: list indices must be integers or slices, not str

The items being iterated over are not integers, and cannot be used as an index to the list.

The following will work for some of the time, but throw an IndexError at the end:

for i in row:
    i2 = int(i)
    row[i2] = i2



回答4:


Given row = ['1', '2', '3'], each item inside row is a string, thus it can be easily printed:

for i in row:
    print(i)

However, in your second example you are trying to access row using a string. You need an integer to access values inside a list, and row is a list! (of strings, but a list still).

for i in row:
    # row[i] = int(row[i])  -> this will throw an error
    row[int(i)] = int(row[int(i)]) # this will throw an error


来源:https://stackoverflow.com/questions/51748786/iterating-over-a-list-in-python-using-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!