基本上:
list1 = ['x', 'y', 'z']
list2 = [1, 2, 3]
我希望我的输出形式为
x
y
y
z
z
z
我有
for i in range(0,len(list1)):
output = list1[i] * list2[i]
print(output)
但这只会让我
x
yy
zzz
您每次都添加相同的字符串,但不会在两者之间进行打印。相反,添加另一个for
循环:
list1 = ['x', 'y', 'z']
list2 = [1, 2, 3]
for i in range(len(list1)):
for x in list1[i] * list2[i]:
print(x)
运行方式为:
>>> list1 = ['x', 'y', 'z']
>>> list2 = [1, 2, 3]
>>> for i in range(len(list1)):
... for x in list1[i] * list2[i]:
... print(x)
...
x
y
y
z
z
z
>>>
另一个建议而不是for i in range(0, len(list1)):
做for i in range(len(list1))
。Python自动将其视为range(0, len(list1))
:
>>> range(0, len(list1))
[0, 1, 2]
>>> range(len(list1))
[0, 1, 2]
>>>
但是,如果你想添加一个跳了range()
,你不需要为包括0
:
>>> range(len(list1), 2)
[]
>>> range(0, len(list1), 2)
[0, 2]
>>>
回答您的评论,使用列表推导将值相乘,然后for
循环显示它们:
list1 = ['xx', 'yy', 'zz']
list2 = [1, 2, 3]
list1 = [list1[i]*list2[i] for i in range(len(list1))]
for k in ''.join(list1):
print k
运行方式为:
>>> list1 = ['xx', 'yy', 'zz']
>>> list2 = [1, 2, 3]
>>> list1 = [list1[i]*list2[i] for i in range(len(list1))]
>>> for k in ''.join(list1):
... print k
...
x
x
y
y
y
y
z
z
z
z
z
z
>>> list1
['xx', 'yyyy', 'zzzzzz']
>>>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句