我正在生成一个字符串并将其附加到列表中。我循环该操作以创建包含 40 个元素的列表。我想像这样打印它们:
这是我的清单
list = [ 'first', 'second', 'third', ... 'fortieth' ]
Run Code Online (Sandbox Code Playgroud)
我试过这个
for z in list:
if z % 2 == 0:
print(list[z], list[z+1])
Run Code Online (Sandbox Code Playgroud)
以及许多其他变体。我希望它像这样打印
first second
third fourth
fifth sixth
...
thirty-ninth fortieth
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?感谢您的时间
在列表上打印 2 个值就像创建一个跳过所有其他值的 for 循环一样简单。当您创建 for 循环时,您可以使用range(start,stop,interval)来完成此操作。然后您可以使用 for 循环填写两个 print 语句
我希望这对您有用:
for x in range(0,len(listtest),2):
print (listtest[x], listtest[x+1])
Run Code Online (Sandbox Code Playgroud)
替换testlist为您的列表名称
| 归档时间: |
|
| 查看次数: |
13974 次 |
| 最近记录: |