如何通过一个循环依次遍历多个列表? [英] How to loop through multiple lists sequentially with one loop?

查看:82
本文介绍了如何通过一个循环依次遍历多个列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.6.3 中,有没有一种方法可以遍历一个列表?

In Python 3.6.3 Is there a way to loop though one list after another?

例如:

deck = [(value, suit) for value in range(2, 11) +
            ["J", "Q", "K", "A"] for suit in ["H", "C", "D", "S"]]

(在这种情况下,我想在非面部卡之后循环遍历面部卡.)

(In this case, I want to loop through the face cards right after the non-face cards.)

为澄清起见: 上一行抛出一个:

For clarification: The above line throws a:

TypeError: unsupported operand type(s) for +: 'range' and 'list'

这是我的问题.

推荐答案

range 在Python3中不会返回list,因此range(2, 10) + ["J", "Q", "K", "A"]不起作用,但list(range(2, 10)) + ["J", "Q", "K", "A"]可以.您还可以使用 itertools.chain 串联可迭代对象:

range doesn't return a list in Python3, so range(2, 10) + ["J", "Q", "K", "A"] doesn't work, but list(range(2, 10)) + ["J", "Q", "K", "A"] does. You can also use itertools.chain to concatenate iterables:

from itertools import chain 

chain(range(2, 10), ["J", "Q", "K", "A"])
# or even shorter:
chain(range(2, 10), "JQKA")  # as strings themselves are iterables

# so this comprehension will work
deck = [
   (value, suit) 
   for value in chain(range(2, 10), "JQKA") 
   for suit in "HCDS"
]

当然,嵌套的理解确实构成了笛卡尔积,您也可以将util用于以下方面:

The nested comprehension does, of course, constitute a cartesian product which you can also use a util for:

from itertools import product
deck = list(product(chain(range(2, 10), "JQKA"), "HCDS"))

这篇关于如何通过一个循环依次遍历多个列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆