有人能解释一下list=[]for uin range(vertex)]是如何工作的吗?

2024-06-16 08:31:03 发布

您现在位置:Python中文网/ 问答频道 /正文

看起来像是打印出了[[],[],[]。在

有人能在不使用列表理解的情况下重新措辞吗?在


Tags: 列表情况措辞
2条回答

如果没有列表理解,它将很简单

is_weighted = False 
is_directed = False 
graph_list = graph_str.splitlines() 
num_verticies = int(graph_list[0].split()[1]) 
graph_list.pop(0)

adj_list = [] #create an empty list to append to

for x in range(num_verticies): #start the for loop
    adj_list.append([]) #append an empty list the num_vertices times

print(adj_list)

您正在创建一个空列表,其大小为顶点。 这些被称为列表理解。在

例如:

foo = [i for i in range(10)]
print(foo)

输出:

^{pr2}$

阅读更多https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions。在

另外,下次发布完整的代码,以便其他人理解和帮助您。在

相关问题 更多 >