简体   繁体   English

如何并行访问两个子列表?

[英]How to iterate through two SUBlists in parallel?

I apologize if there is a duplicate, but I searched and could not find any topics that address my current issue. 如有重复,我深感抱歉,但我进行了搜索,但找不到解决我当前问题的任何主题。

I want to know if there is some pythonic way to iterate through two (or more) sublists in parallel. 我想知道是否有某种pythonic方式可以并行访问两个(或多个)子列表。 I'm already well aware of the zip function, so I will use it in a short example to explain what I want to do. 我已经非常了解zip功能,因此我将在一个简短的示例中使用它来解释我想要做什么。 Let's say I have the following two lists: 假设我有以下两个列表:

list1 = [1,2,3]
list2 = [4,5,6]

I know that I can iterate through them simultaneously like this: 我知道我可以像这样同时遍历它们:

>>> newlist = [i+j for i,j in zip(list1, list2)]
>>> newlist
[5,7,9]

However, with the way my data is being handled, I would like to do something slightly different. 但是,通过我的数据处理方式,我想做些不同的事情。 Instead of two independent lists, my data storage looks more like this: 而不是两个独立的列表,我的数据存储看起来像这样:

biglist = [[1,2,3], [4,5,6]]

I know I could extract each sublist to be it's own variable, but I was moreso hoping I could do something more like this: 我知道我可以提取每个子列表作为它自己的变量,但是我还是希望可以做更多这样的事情:

newbiglist = [i+j for i,j in zip(biglist)]

Where python would be able to recognize that there are two sublists in biglist . python能够识别biglist有两个子列表的biglist Does anyone know of any function that could do something like this? 有谁知道可以执行类似操作的功能吗?

Have you tried 你有没有尝试过

newbiglist = [i+j for i,j in zip(*biglist)]

The "star" or "splat" operator * splits the variable into its components for use as parameters. “ star”或“ splat”运算符*将变量拆分为其组件,以用作参数。

The result then of 然后的结果

print(newbiglist)

is what you want: 是您想要的:

[5, 7, 9]

Note that this will give an error if biglist contains something other than two lists. 请注意,如果biglist包含两个列表以外的内容,则会产生错误。 There are several ways to handle a differing number of lists: the answer by @crook handles that nicely, and there are other ways. 有几种方法可以处理不同数量的列表:@crook的答案可以很好地处理列表,还有其他方法。

for two or more you could try this 两个或两个以上您可以尝试

[sum(i) for i in  zip(*biglist)]

here i will be iterable, so you can use any function which accepts iterable or you can write your own. 在这里i将是可迭代的,因此您可以使用任何接受可迭代的函数,也可以编写自己的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM