Python:如何将一个列表和一个列表一起映射 [英] Python: how to map one list and one list of list together

查看:98
本文介绍了Python:如何将一个列表和一个列表一起映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图通过map()摆脱一些嵌套循环,并遇到特定情况的麻烦.

So I'm trying to get rid of some nested loops through map() and have trouble with a specific case.

我有两个列表:

列表1 = [1、2、3、4、5]

List1 = [1, 2, 3, 4, 5]

List2 = [[1、2、3],[5],[1、6],[1、0、9、10],[1、5、2]]

List2 = [[1, 2, 3], [5], [1, 6], [1, 0, 9, 10], [1, 5, 2]]

因此,基本上list1和list 2的长度是相同的,但是list 2是可变长度的列表的列表.

So basically list1 and list 2 are the same lengths, but list 2 is a list of lists of variable lengths.

我想调用等效的功能;

I want to call some function on the equivalent of;

(1,1),(1,2),(1,3),(2,5),(3,1),(3,6),(4,1),(4,0) ,(4,9)(4,10),(5,1),(5,5),(5,2)

(1,1), (1,2), (1,3), (2,5), (3,1), (3,6), (4,1), (4,0), (4,9) (4,10), (5,1), (5,5), (5,2)

使用地图.元组的第一个参数来自List1,第二个参数来自list2上list1的第i个等价项,其中子列表已展开.

using map. The first parameter of the tuple is from List1 and the second one is from the i'th equivalent of list1 on list2, with the sublist expanded.

现在我有:

地图(函数,邮政编码(列表1,列表2))

map(function, zip(list1, list2))

但是我看不到如何扩展list2以获得我刚刚描述的内容.我认为这可能涉及列表理解,但是我遇到了一些麻烦,反复试验并没有使我走得太远.

but I cannot see how I could expand list2 to get what I just described. I think it might involve list comprehensions, but I'm having a little trouble and trial and error didn't get me very far.

另一个问题是,如果此嵌套循环中的内部函数易于被调用数百万次,那么map()会比for循环快得多吗?

Another question is, if the inner function in this nested loop is susceptible to get called millions of times, will map() be significantly faster than just a for loop?

推荐答案

列表理解很简单,就像这样

Its simple with list comprehension, like this

list1 = [1, 2, 3, 4, 5]
list2 = [[1, 2, 3], [5], [1, 6], [1, 0, 9, 10], [1, 5, 2]]
print [(item1, s) for item1, item2 in zip(list1, list2) for s in item2]

输出

[(1, 1), (1, 2), (1, 3), (2, 5), (3, 1), (3, 6), (4, 1), (4, 0), (4, 9), (4, 10), (5, 1), (5, 5), (5, 2)]

此oneliner只是的简短版本

This oneliner is just a short version of

result = []
for item1, item2 in zip(list1, list2):
    for s in item2:
        result.append((item1, s))

这篇关于Python:如何将一个列表和一个列表一起映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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