0

这些是我的清单

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

我希望我的输出是这样的,

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

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

4

5 回答 5

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

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

感谢@JonClements 和@DSM 的建议。

于 2013-08-29T11:05:26.010 回答
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.

于 2013-08-29T11:04:29.053 回答
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']
于 2013-08-29T11:04:14.193 回答
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']
于 2013-08-29T11:04:51.960 回答
0

尝试这个:

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

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

于 2013-08-29T11:06:53.447 回答