【问题标题】:How to apply a function on a list of lists two at a time? [closed]如何一次对两个列表应用函数? [关闭]
【发布时间】:2017-08-26 09:27:59
【问题描述】:

我有一个这样的列表:

all_lists = [list0, list1, list2, list3, ....., listn]

还有一个像这样的函数,它从这个 all_lists 中获取两个参数。

def function(list0, list1):
    do stuff

该函数将通过将索引移动 1 直到到达 listn 来继续从该 all_lists 中获取参数。

有没有一种有效的方法来做到这一点? 谢谢!

【问题讨论】:

  • 两个参数表示所有组合,如function(list0 ,list1) 或function(list0 ,list2)

标签: python list apply sublist


【解决方案1】:

zip 带有自身的列表并在循环中传递参数。

for l1, l2 in zip(all_lists[:-1], all_lists[1:]): # or zip(all_lists, all_lists[1:])
    function(l1, l2)

MVCE:

lst = [1, 2, 3, 4]

for i, j in zip(lst, lst[1:]):
    print(i, j)

1 2
2 3
3 4

【讨论】:

  • 你不需要[:-1],所以充其量是一个VCE :-P
  • @StefanPochmann 来自 Python 之禅:Explicit is better than implicit. ... :p
  • 嗯,这只是第二个。首先是Beautiful is better than ugly.
  • @StefanPochmann ahaha Nitpick 已接受。
【解决方案2】:

如果你想要所有可能的组合,你可以使用 itertools combination 方法

>>> import itertools
>>> a = [[1,2],[2,3],[3,4]]
>>> 
>>> for _lst in itertools.combinations(a, 2):
...      print _lst
... 
([1, 2], [2, 3])
([1, 2], [3, 4])
([2, 3], [3, 4])

对于您的代码:

all_lists = [list0, list1, list2, list3, ....., listn]

for l1,l2 in itertools.combinations(all_list , 2):
    print l1,l2
    # do stuff

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 2021-11-29
    • 1970-01-01
    • 2014-07-31
    • 2014-08-10
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    相关资源
    最近更新 更多