Python - 插入列表

时间:2015-11-26 03:18:24

标签: python

我从csv文件中获取一个数组,然后得到一个类似于

的列表
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.insert(index, item)
    i += 0

它没有改变my_list是一样的吗?

我该如何更改?

由于

5 个答案:

答案 0 :(得分:3)

试试这个:

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

你没有递增变量i,而insert()将项目向右移动,它不会替换它们。当然,更惯用的解决方案是:

my_list = my_list[:8] + new_array

答案 1 :(得分:0)

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

输出:

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]

答案 2 :(得分:0)

这样的事情:

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

答案 3 :(得分: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]

答案 4 :(得分: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]

OR

>>> 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]