如何将列表中的值插入到空间位置的其他位置?

时间:2013-08-29 10:56:03

标签: python

这些是我的清单

i=["abc","def","ghi"]
j=[" ","rfd"," "," ","qf"]

我希望我的输出像这样,

j=["abc","rfd","def","ghi","qf"]

,即每当它在“j”中找到空格时,它应该用“i”中的元素替换空格? 如何将列表中的值插入到空间位置的其他位置

5 个答案:

答案 0 :(得分:4)

it= iter(i)
[next(it) if item.isspace() else item for item in j]

如果它不是“空”(所有空格),这将迭代j列表并产生元素。如果它是“空”,它将产生i列表的下一个元素。

感谢@JonClements和@DSM的建议。

答案 1 :(得分:3)

怎么样:

i=["abc","def","ghi"]
j=[" ","rfd"," "," ","qf"]

filler = iter(i)
print [el if el != ' ' else next(filler, ' ') for el in j]
# ['abc', 'rfd', 'def', 'ghi', 'qf']

取消默认参数(例如:next(filler)),如果j中有空格但i没有其他替代品,则应发生例外。

答案 2 :(得分:0)

这不是一个非常常见的问题:

i=["abc","def","ghi"]
j=[" ","rfd"," "," ","qf"]


while " " in j and i:
    j[j.index(" ")] = i.pop(0)

print j
Output: ['abc', 'rfd', 'def', 'ghi', 'qf']

答案 3 :(得分:0)

理解的简单明了的解决方案:

>>> i = ['abc', 'def', 'ghi']
>>> j = [' ', 'rfd', ' ', ' ', 'qf']
>>> cnt = 0
>>> new = []
>>> for item in j:
...     if item == ' ':
...             new.append(i[cnt])
...             cnt += 1
...     else:
...             new.append(item)
... 
>>> print new
['abc', 'rfd', 'abc', 'abc', 'qf']

答案 4 :(得分:0)

试试这个:

[x for x in (i + j) if len(x.strip()) > 0]

使用列表理解的简单解决方案。