具有多个循环的 Python 列表理解

标签 python list list-comprehension

我的目标是创建一个单行以生成以下列表:

list_100 = ['ch1%.2d' % x for x in range(1,6)]
list_200 = ['ch2%.2d' % x for x in range(1,6)]

final_list = list_100 + list_200
[ch101,ch102,ch103,ch104,ch105, ch201,ch202,ch203,ch204,ch205]

有没有办法在一行中做到这一点:

final_list = ['ch%.1d%.2d' % (y for y in range(1,3), x for x in range(1,6)]

最佳答案

你们非常亲密:

>>> ['ch%.1d%.2d' % (y, x) for y in range(1,3) for x in range(1,6)]
['ch101',
 'ch102',
 'ch103',
 'ch104',
 'ch105',
 'ch201',
 'ch202',
 'ch203',
 'ch204',
 'ch205']

关于具有多个循环的 Python 列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51391300/

相关文章:

python - 我需要你关于 python pandas 中 read_fwf 的帮助

python - multiprocessing.Pool 示例

list - 如何在 SwiftUI 的列表中启用选择

for-loop - 了解 Clojure 中的列表理解修饰符顺序

python - 在列表理解中使用 OR

python - Celey + Python 忽略 update_state 调用

python - 如何检索 FFMPEG(从 OpenCV 调用)Python 解码错误

list - python : create a pandas data frame from a list

python - 有没有办法按索引合并多个列表索引?

python - 如何从 Python 中的 SQLite3 数据库查询构建字典列表?