繁体   English   中英

python用循环附加到嵌套列表

[英]python appending to nested list with loop

我是 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)

以这种方式使用大量变量是一个坏主意。 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 中一个非常重要的对象。

我希望我回答了你的问题。

如果您有问题,请告诉我

输出,将是这样的嵌套列表:

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

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

这里以使用您的代码为例

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM