Python - paste to list

I get an array of the form of the csv file, and I get a list that looks like

my_list = ["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', '', '', '', '', '', '', '', '']

And now I want to fill in the spots where there is ''an array of elements whose length is equal, which allows me to say that the array I want to add is

new_array = [1,2,3,4,5,6,7,8]

this is what i am trying, but it does not work.

i = 0
for item in new_array:
    index = 8+i
    print item
    my_list.insert(index, item)
    i += 0

Does this change my_list nothing the same way?

How can i change this?

thanks

+4
source share
5 answers

Try the following:

i = 8
for item in new_array:
    my_list[i] = item # you want to replace the value
    i += 1            # you forgot to increment the variable

You did not increase the variable i, but insert()moved the elements to the right, they did not replace them. Of course, a more idiomatic solution would be:

my_list = my_list[:8] + new_array
+3
source
my_list = ["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', '', '', '', '', '', '', '', '']
new_array = [1,2,3,4,5,6,7,8]
i = 0
for item in new_array:
    index = 8+i
    print item
    my_list.remove('')
    my_list.insert(index, item)
    i += 1
print my_list

exit:

1
2
3
4
5
6
7
8
["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', 1, 2, 3, 4, 5, 6, 7, 8]
0
source

- :

new_iter = iter(new_array)
my_list = [i if i != '' else next(new_iter) for i in my_list]
print(my_list)
0

'' ( ), :

my_list = ["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', '', '', '', '', '', '', '', '']

starts_at = my_list.index('')
amount_of_empty_strings = 0

for i, item in enumerate(my_list):
    if item.strip() == "":
        my_list[amount_of_empty_strings+starts_at] = amount_of_empty_strings+1
        amount_of_empty_strings+=1

print my_list

:

["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', 1, 2, 3, 4, 5, 6, 7, 8]
0

>>> new_array = [1,2,3,4,5,6,7,8]
>>> new_array.reverse()
>>> new_array
[8, 7, 6, 5, 4, 3, 2, 1]
>>> [new_array.pop()  if item is '' else item  for item in my_list]
["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', 1, 2, 3, 4, 5, 6, 7, 8]

>>> from collections import deque
>>> new_array = deque([1,2,3,4,5,6,7,8])
>>> [new_array.popleft()  if item is '' else item  for item in my_list]
["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', 1, 2, 3, 4, 5, 6, 7, 8]
0

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


All Articles