python使用循环附加到嵌套列表

2024-06-17 12:45:49 发布

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

我是Python新手。我有下面的嵌套列表,我正在使用多个append语句向嵌套列表添加项。如何仅使用一个append语句和一个循环将列表追加到嵌套列表中?假设我有多达s100(s1、s2、…s100)个这样的单独列表,我将添加到嵌套列表中。我目前的代码如下:

s1= ["sea rescue","rescue boat", "boat"]
s2=["water quality","water pollution","water"]
nestedlist=[]    
nestedlist.append(s1)
nestedlist.append(s2)
print(nestedlist)

Tags: 代码列表语句qualitys2append新手water
2条回答

可以使用extend()方法并在列表中指定参数

下面是使用您的代码的示例

s1= ["sea rescue","rescue boat", "boat"]
s2=["water quality","water pollution","water"]
nestedlist=[]    
nestedlist.extend([s1,s2])
print(nestedlist)

以这种方式使用大量变量是个坏主意。Python为此提供了一些奇妙的东西。格言。您可以将变量名用作键,将列表用作值

大概是这样的:

foo = dict(s1= ["sea rescue","rescue boat", "boat"],
    s2 = ["water quality","water pollution","water"])

nestedlist= []

for bar in foo.values():

nestedlist.append(bar)

print(nestedlist)

这将为您节省大量内存和代码,最终使您的代码更易于阅读。内存引用也不会捕获100个变量

我强烈建议您学习dict,因为它在python中是一个非常重要的对象

我希望我回答了你的问题

如果你有问题,请告诉我

输出将是一个嵌套列表,如下所示:

[['海上救援'、'救援船'、'船']、['水质'、'水污染'、'水']

相关问题 更多 >