Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python双列表洗牌_Python_List - Fatal编程技术网

Python双列表洗牌

Python双列表洗牌,python,list,Python,List,我有两份清单: a = [1, 2, 3, 4] b = [5, 6, 7, 8] 我需要这样的东西: c = [1, 5, 2, 6, 3, 7, 4, 8] 我使用这个解决方案: c = list(reduce(lambda x, y: x + y, zip(a, b))) 有更好的方法吗?使用chain: from itertools import chain, izip interweaved = list(chain.from_iterable(izip(a, b))) # [1

我有两份清单:

a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
我需要这样的东西:

c = [1, 5, 2, 6, 3, 7, 4, 8]
我使用这个解决方案:

c = list(reduce(lambda x, y: x + y, zip(a, b)))

有更好的方法吗?

使用
chain

from itertools import chain, izip
interweaved = list(chain.from_iterable(izip(a, b)))
# [1, 5, 2, 6, 3, 7, 4, 8]
使用列表理解:

上述嵌套列表理解相当于以下嵌套for循环(以防混淆):

同样可行的是:

list(sum(zip(a, b), ()))

如果你想得到确切的结果,那么“shuffle”不是一个got词,因为它表示随机顺序。如果你想要随机顺序,你的例子就不是很幸运了。请具体说明,你指的是哪一种。@kratenko:你能推荐一个更好的术语来描述这种特殊的混合物吗?我第一次尝试“合并”,但我在这里的搜索结果更接近“总和”。尝试“洗牌”(如洗牌)让我来到这里,这正是我想要的。为了清楚起见,请添加嵌套的for循环来解释这实际上是如何工作的。我肯定有很多人在说等等。。。什么?当他们第一次看到这个:)@Kimvais。你指的是循环的一般形式吗?是的。新手需要眯起眼睛很难弄清楚哪一个是内部for循环,哪一个是外部for循环,以及进入
tup
:)@Kimvais的是什么。补充。谢谢:)不,差不多一样,在我的机器上也快一点。理解力在更大的列表中获胜。
result = []
for tup in zip(a, b):
    for x in tup:
        result.append(x)
list(sum(zip(a, b), ()))