【问题标题】:python appending to nested list with looppython用循环附加到嵌套列表
【发布时间】:2020-02-09 14:21:28
【问题描述】:

我是 Python 新手。我有以下嵌套列表,我正在使用多个附加语句将项目添加到嵌套列表中。如何只使用一个附加语句和一个循环将列表附加到嵌套列表中?假设我有多达 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 loops nested-lists


    【解决方案1】:

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

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

    如果您有任何问题,请告诉我

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

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

    【讨论】:

    • 非常感谢。我会试试的。
    【解决方案2】:

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

    这里以您的代码为例

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

    【讨论】:

    • 谢谢。我希望我可以使用 s+loopvariable (=s1,s2..) 之类的东西
    猜你喜欢
    • 1970-01-01
    • 2022-07-14
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多