在列表理解中增加和迭代

时间:2015-10-13 22:45:49

标签: python

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'

如何在列表理解中执行此操作?在循环中这样做更好吗?

1 个答案:

答案 0 :(得分:3)

t = [s%(x[0],e,w) for i in x]替换为t = [s%(i,e,w) for i in x];你没有迭代x