Python-My for loop only converts half the list from str to int

I want my code to loop through each element of the list and convert it from str to int, but it only converts half the list and in irregular order. My code is:

for item in list:
    list.append(int(item))
    list.remove(item)
print (list)

For example, if the list is [5, 6, 3, 5, 6, 2, 6, 8, 5, 2 ',' 8 ']

The final will be ['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]

Which is only half converted and out of order.

I could have done it differently, but it is much longer, so I would like to fix it and add to my knowledge of cycles.

My knowledge and experience with Python is tiny, so I probably won’t understand if it’s not explained that this is really basic and jargon.

+4
source share
5 answers

Using list comprehension :

l = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']

output = [int(i) for i in l]
print(output)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]

If you do not understand the list comprehension, you can use a simple loop for:

l1 = []
for i in l:
     l1.append(int(i))

print(l1)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
+4
source

Why don't you use something like this:

l = list(map(int, l))

It simply calls a function intfor each item from l. Here is the doc .

+2
source

, , .

-, . , . , , , .

-, remove , , , .

-, . .

for item in list:
    print (list)
    list.append(int(item))
    list.remove(item)

# Prints
['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
['6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5]
['6', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3]
['5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6]
['5', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6]
['2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5]
['6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5, 2]
['6', '8', '5', '4', '2', '8', 3, 6, 6, 5, 2, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 5, 2, 5, 6]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 5, 6, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]

,

+2

, . , () , for. ( ), item . item .

: . .

, , :

for i in xrange(len(l)):
    l[i] = int(l[i])

:

for item in l:
   item = int(item)

It does not mutate individual elements of the list, even if you think so. This is due to how Python iterators work.

0
source

Try the following:

>>> list = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
>>> for item in list[:]:
...     list.append(int(item))
...     list.remove(item)
... 
>>> print(list)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]

Explanation: Here we iterate over the clone of the list, but do the operations in the original list.

PS: listis a keyword in python. Its use as a variable name should be avoided.

0
source

Source: https://habr.com/ru/post/1621803/


All Articles