Python中许多列表的串联 [英] Concatenation of many lists in Python

查看:50
本文介绍了Python中许多列表的串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的函数:

Suppose I have a function like this:

def getNeighbors(vertex)

返回与给定顶点相邻的顶点列表.现在,我想创建一个包含所有邻居的列表.我这样做是这样的:

which returns a list of vertices that are neighbors of the given vertex. Now I want to create a list with all the neighbors of the neighbors. I do that like this:

listOfNeighborsNeighbors = []
for neighborVertex in getNeighbors(vertex):
    listOfNeighborsNeighbors.append(getNeighbors(neighborsVertex))

有没有更多的Python方式来做到这一点?

Is there a more pythonic way to do that?

推荐答案

[x for n in getNeighbors(vertex) for x in getNeighbors(n)]

sum(getNeighbors(n) for n in getNeighbors(vertex), [])

这篇关于Python中许多列表的串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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