python - Python中的嵌套循环
问题描述
我正在学习 Python 循环。在下面的代码中,我无法获得所需的输出。
我想将两个嵌套列表值分成两行代码:
list_of_list = [[1,2,3],[4,5,6]]
for list1 in list_of_list:
print (list1)
for x in list1:
print (x)
期望的输出:
[1, 2, 3]
[4, 5, 6]
我当前的输出:
1
2
3
4
5
6
请就如何达到预期结果提出建议。
解决方案
几种方式:
1.join
做:
print('\n'.join([str(i) for i in list_of_list]))
2.list comprehension
做:
[print(i) for i in list_of_list]
3.for-loop
做:
for i in list_of_list:
print(i)
所有输出:
这个:
[1, 2, 3]
[4, 5, 6]
如预期的
解释为什么你的不起作用:
因为循环太多,只需要一个循环
外循环足以满足需要,您有嵌套循环,所以第一个循环(我的意思是外循环)
推荐阅读
- amazon-s3 - 我在 CDN 服务器 (Amazon S3) 上上传 CSS 和字体文件并发现这些错误。请建议我能做些什么来解决它
- ios - SwiftUI 代码在 iphone 中运行,但在 ipad 中出现黑屏?
- java - 在 Spring 中使用第三方代码处理事务
- angular-ui-router - IdentityServer4 在 LoginUrl 中编码 #
- c# - 如何 pxselect 并将其放在 var 上
- ffmpeg - 如何在 FFmpeg 的视频中为具有文本大小的文本添加背景图像?
- algorithm - 证明从 x 开始的任何子树的红黑树至少包含 2^bh(x)-1 个内部节点。(不是通过归纳)
- python - Django:保存表单不起作用(ModelForm 通过 request.user 过滤 ForeignKey 选择)
- tsql - SQL - 从条件开始添加顺序计数器列,具有分组和非递增 ID
- jquery - 如何在固定导航栏下方通过选取框而不中断导航栏内容