我想创建一个输出,将列表和元组连接起来以提供单个输出
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
为什么我不递增。我做错了什么
问题:
- 您定义了内部循环
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])