x = ['a','b','c','y','h']
e = 'fork'
w = 'knife'
s = 'what %s is the %s doing inside the %s'
t = [s%(x[0],e,w) for i in x]
print t
如果我运行上面的代码,我会得到类似的内容:
'what a is the for doing inside the knife'
重复了x中元素的次数。我想要做的是迭代x,以便输出类似于:
'what a is the fork doing inside the knife','what b is the fork doing inside the knife'
'what c is the fork doing inside the knife','what y is the fork doing inside the knife',
'what h is the fork doing inside the knife'
如何在列表理解中执行此操作?在循环中这样做更好吗?
答案 0 :(得分:3)
将t = [s%(x[0],e,w) for i in x]
替换为t = [s%(i,e,w) for i in x]
;你没有迭代x
。