这些是我的清单
i=["abc","def","ghi"]
j=[" ","rfd"," "," ","qf"]
我希望我的输出是这样的,
j=["abc","rfd","def","ghi","qf"]
即,每当它在“j”中找到空格时,它应该用“i”中的元素替换空格吗?如何将列表中的值插入到其他空间位置
这些是我的清单
i=["abc","def","ghi"]
j=[" ","rfd"," "," ","qf"]
我希望我的输出是这样的,
j=["abc","rfd","def","ghi","qf"]
即,每当它在“j”中找到空格时,它应该用“i”中的元素替换空格吗?如何将列表中的值插入到其他空间位置
it= iter(i)
[next(it) if item.isspace() else item for item in j]
j
如果它不是“空”(所有空格),这将遍历列表并产生元素。如果它是“空的”,它将产生i
列表的下一个元素。
感谢@JonClements 和@DSM 的建议。
怎么样:
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
.
嗯不是一个很常见的问题:
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']
一个很好且易于理解的解决方案:
>>> 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']
尝试这个:
[x for x in (i + j) if len(x.strip()) > 0]
使用列表理解的简单解决方案。