我想创建一个将列表和元组连接在一起的输出,以提供单个输出
def conca(names,storey):
for name in names:
i = 0
d = "%s has %d"%(name,storey[i])
print(d)
i = i+1
conca(names=("White house","Burj khalifa",
"Shit"),storey = [3,278,45])
但是它给出的输出是
白宫有3
哈利法塔有3个
狗屎有3
但是我不想要3。我希望我增加。提供类似
的输出白宫有3
哈利法塔有278名
狗屎有45
我为什么不增加。我在做什么错
答案 0 :(得分:1)
问题:
i
,因此每次迭代都将其重置为0,从而导致每次都添加第一个storey
。更正:
def conca(names, storey):
i = 0
for name in names:
d = "%s has %d"%(name,storey[i])
print(d)
i = i+1
conca(names=("White house","Burj khalifa",
"Shit"), storey=[3,278,45])
您还可以使用zip()
同时遍历列表:
def conca(names, storey):
for name, st in zip(names, storey):
print(f'{name} has {st}')
conca(names=("White house","Burj khalifa",
"Shit"), storey=[3,278,45])